请老师检查~
来源:5-3 自由编程
晓舟
2021-07-02 18:52:25
package com.imooc.weather;
import java.util.Random;
public class Weather {
private int temperature;
private int humdity;
boolean flag = false;
Random rand = new Random();
public synchronized void generate() {
if(flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setTemperature(rand.nextInt(41));
this.setHumdity(rand.nextInt(101));
System.out.println("生成"+this);
notifyAll();
flag=true;
}
public synchronized void read() {
if(!flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("读取"+this);
notifyAll();
flag=false;
}
@Override
public String toString() {
return "天气数据 [温度:"+this.getTemperature()+",湿度"+this.humdity+"]";
}
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public int getHumdity() {
return humdity;
}
public void setHumdity(int humdity) {
this.humdity = humdity;
}
}
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++) {
weather.read();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
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++) {
weather.generate();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
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();
}
}
1回答
同学你好,测试代码是正确的,完成的很棒!继续加油!
祝学习愉快~
相似问题