练习打卡,请老师检查~
来源:5-3 自由编程
Heijyu
2020-06-19 14:13:22
package com.imooc.exercise_5_3;
import java.util.Random;
public class Weather {
// 包含int类型的温度(temperature)和湿度(humidity)属性,以及布尔类型的属性flag
private int temperature;
private int humidity;
boolean flag = false;
// 构造方法
public Weather() {
this(0,0);
}
public Weather(int temperature, int humidity) {
this.setTemperature(temperature);
this.setHumidity(humidity);
}
// 温度和湿度属性的getter和setter方法
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 void generate()
public synchronized void generate() {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.setTemperature((int) (Math.random() * 40));
this.setHumidity((int) (Math.random() * 100));
System.out.println("生成天气数据:" + this.toString());
flag = true; // 生成完毕,容器有数据
notifyAll();
}
// 读取天气数据的方法public void read() 读取天气数据
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();
}
// 重写toString()方法
@Override
public String toString() {
return "[温度:" + this.getTemperature() + ", 湿度:" + this.getHumidity() + "]";
}
}
package com.imooc.exercise_5_3;
public class GenerateWeather implements Runnable {
Weather weather;
GenerateWeather(Weather weather) {
this.weather = weather;
}
@Override
public void run() {
int i = 0;
while (i <= 100) {
weather.generate();
i++;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.imooc.exercise_5_3;
public class ReadWeather implements Runnable {
Weather weather;
ReadWeather(Weather weather) {
this.weather = weather;
}
@Override
public void run() {
int i = 0;
while (i <= 100) {
weather.read();
i++;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.imooc.exercise_5_3;
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();
}
}1回答
同学你好,按照练习需求建议同学在生成天气数据睡眠5秒的时间,在读取数据睡眠0.1秒的时间。建议在循环中调用sleep()方法。修改后代码如下所示:


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