老师,请检查

来源:5-3 自由编程

阿山123

2021-04-01 13:18:36

package com.imooc.weather;

public class Weather {
private int temperature;// 温度
private int humidity;// 湿度

public Weather() {

}

public Weather(int temperature, int humidity) {

this.setTemperature(temperature);
this.setHumidity(humidity);
}

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;
}

boolean flag = true;

public synchronized void generate() {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

this.temperature = (int) (Math.random() * 41);
this.humidity = (int) (Math.random() * 101);
System.out.println("生成天气数据:"+toString());
flag = false;
notifyAll();

}

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

flag = true;
notifyAll();
}

@Override
public String toString() {
return " [温度:" + temperature + ", 湿度:" + humidity + "]";
}

}
package com.imooc.weather;

public class GenerateWeather implements Runnable {

Weather weather;

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

@Override
public void run() {
for(int i=1;i<=100;i++) {

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

weather.generate();

}

}

}
package com.imooc.weather;

public class ReadWeather implements Runnable {
Weather weather;

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

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

weather.read();

}

}

}
package com.imooc.weather;

public class WeatherTest {

public static void main(String[] args) {
Weather weather=new Weather();
GenerateWeather genwt=new GenerateWeather(weather);
ReadWeather rewt=new ReadWeather(weather);
Thread thgen=new Thread(genwt);
Thread thre=new Thread(rewt);

thgen.start();
thre.start();
}

}


写回答

1回答

好帮手慕阿慧

2021-04-01

同学你好,练习题完成的不错,很棒,继续加油!祝学习愉快~

0

0 学习 · 16556 问题

查看课程