栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java多线程练习天气生成(5s)获取(0.1s)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java多线程练习天气生成(5s)获取(0.1s)

 

 

 

 

 

 下面是源代码

package per.llldf.lx;

public class Weather {
	private int humidity;
	private int temperature;
	boolean flag = false;
	
	public Weather() {
		
	}
	
	public int getHumidity() {
		return humidity;
	}
	public void setHumidity(int humidity) {
		this.humidity = humidity;
	}
	public int getTemperature() {
		return temperature;
	}
	public void setTemperature(int temperature) {
		this.temperature = temperature;
	}
	@Override
	public String toString() {
		return " [湿度:" + humidity + ", 温度:" + temperature + "]";
	}
	
	public synchronized void get() {
		if (!flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}}
		System.out.println("获取的天气:" + this);
		flag = false;
		notifyAll();
	}
	public synchronized void gene() {
		if (flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}}
		this.setHumidity(((int)(Math.random() * 101)));
		this.setTemperature(((int)(Math.random() * 41)));
		System.out.println("生成的天气:" + this);
		flag = true;
		notifyAll();
	}
}
package per.llldf.lx;

public class Gene implements Runnable{
	Weather w;
	Gene(Weather w){
		this.w = w;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 100; i++) {
		w.gene();
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}}
	
}
package per.llldf.lx;

public class Read implements Runnable{
	Weather w;
	Read(Weather w){
		this.w = w;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 100; i++) {
		w.get();
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}}
	
}
package per.llldf.lx;

public class Test {
	public static void main(String[] args) {
		Weather w = new Weather();
		new Thread(new Gene(w)).start();
		new Thread(new Read(w)).start();
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424035.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号