5-3编程练习请老师检查

来源:5-3 自由编程

weixin_慕村4552609

2021-12-20 23:40:17

package com.imooc.weather;

public class WeatherTest {

	public static void main(String[] args) {
		Weather weather = new Weather();
		new Thread(new GenerateWeather(weather)).start();
		new Thread(new ReadWeather(weather)).start();
	}

}


package com.imooc.weather;

public class Weather {
	private int temperature;
	private int humidity;
	private boolean flag = false;

	public int getTemperature() {
		return temperature;
	}

	public void setTemperature(int temperature) {
		this.temperature = temperature;
	}

	public int getHumidity() {
		return humidity;
	}

	public void setHumidity(int humidity) {
		this.humidity = humidity;
	}

	public synchronized void generate() {
		if (flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		temperature = (int) (Math.random() * 40);
		humidity = (int) (Math.random() * 100);
		System.out.println("生成天气数据" + toString());
		flag = true;
		notifyAll();
	}

	public synchronized void read() {
		if (!flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("读取天气数据" + toString());
		flag = false;
		notifyAll();
	}

	@Override
	public String toString() {

		return "[温度:" + temperature + ",湿度:" + humidity + "]";
	}

}


package com.imooc.weather;

public class GenerateWeather implements Runnable {
	private Weather weather;

	public GenerateWeather(Weather weather) {
		this.weather = weather;
	}

	@Override
	public void run() {
		int i = 0;
		while (i < 100) {
			weather.generate();
			i++;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}


package com.imooc.weather;

public class ReadWeather implements Runnable {
	private Weather weather;

	public ReadWeather(Weather weather) {
		this.weather = weather;
	}

	@Override
	public void run() {
		weather.read();
		int i = 0;
		while (i < 100) {
			weather.read();
			i++;
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}


写回答

1回答

好帮手慕小蓝

2021-12-21

同学你好,同学的代码符合题目要求,逻辑清晰,书写规范,做的很棒。

祝学习愉快~


0

0 学习 · 16556 问题

查看课程