请问该代码是否符合条件要求?

来源:5-3 自由编程

帅7东东

2021-09-01 05:21:15

相关代码:

package com.imooc.weather;

public class Weather {
//私有属性:温度,湿度
private int temperature;
private int humidity;
boolean flag=false;

//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(), 使用随机数获取0-40度之间的温度,0-100之间的湿度.
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=false;
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 " [温度:" + temperature + ", 湿度:" + humidity + "]";

}


}

相关代码:

package com.imooc.weather;

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.weather;

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.weather;

public class Test {

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

}


写回答

1回答

好帮手慕小小

2021-09-01

同学你好,代码整体完成的很好,但还存在一点小问题,当执行完读取天气数据的方法public void read()后flag应设置为true,如下:

https://img.mukewang.com/climg/612ee6760905f82605110646.jpg

祝学习愉快~

0

0 学习 · 9886 问题

查看课程