老师好~帮忙检查一下作业

老师好~帮忙检查一下作业


public class Weather {

private int temperature;

private int humidity;

boolean flag = false;


public Weather() {

super();

}


public Weather(int departure, int humidity) {

super();

this.temperature = departure;

this.humidity = humidity;

}


public int getDeparture() {

return temperature;

}


public void setDeparture(int departure) {

this.temperature = departure;

}


public int getHumidity() {

return humidity;

}


public void setHumidity(int humidity) {

this.humidity = humidity;

}


public synchronized void read() {

if (!flag) {

try {

wait();

} catch (InterruptedException e) {

// TODO 自动生成的 catch 块

e.printStackTrace();

}


}

this.getDeparture();

this.getHumidity();

flag = false;

System.out.println("读取天气数据" + this.toString());

notifyAll();


}


public synchronized void generate() {

if (flag) {

try {

wait();

} catch (InterruptedException e) {

// TODO 自动生成的 catch 块

e.printStackTrace();

}


}

this.setDeparture((int) ((Math.random()) * 40));

this.setHumidity((int) ((Math.random()) * 100));

flag = true;

System.out.println("生成天气数据" + this.toString());

notifyAll();

}


@Override

public String toString() {

return "[温度:" + this.getDeparture() + ", 湿度:" + this.getHumidity() + "]";

}


}

public class GenerateWeather implements Runnable {
Weather w ;

	public GenerateWeather(Weather w) {
	super();
	this.w = w;
}

	@Override
	public void run() {
		// TODO 自动生成的方法存根
for(int i =0;i<100;i++) {
			w.generate();
			
	try {
	Thread.sleep(5000);
} catch (InterruptedException e) {
	// TODO 自动生成的 catch 块
	e.printStackTrace();
	}


}
	}

}

public class ReadWeather implements Runnable {
	Weather w;

	public ReadWeather(Weather w) {
		super();
		this.w = w;
	}

	@Override
	public void run() {
		// TODO 自动生成的方法存根
		for (int i = 0; i < 100; i++) {
			w.read();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

		}

	}
}

public class WeatherTest {

	public static void main(String[] args) {
		Weather w = new Weather();
		GenerateWeather g = new GenerateWeather(w);
		ReadWeather r = new ReadWeather(w);
		Thread i1 = new Thread(g);
		Thread i2 = new Thread(r);
		i1.start();
		i2.start();
	}
}


正在回答

登陆购买课程后可参与讨论,去登陆

1回答

同学你好,代码完成的不错!继续努力!

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!


问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师