老师请问出现了一次生成多次读取的结果,该怎么解决

来源:5-3 自由编程

慕桂英0440464

2021-08-15 10:03:02

package com.imooc.homeworktest;

public class GenerateWeather implements Runnable {
Weather weather;

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


@Override
public void run() {
while(true) {
weather.generate();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}


package com.imooc.homeworktest;

public class ReadWeather implements Runnable {
Weather weather;

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

@Override
public void run() {
while(true) {
weather.read();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}


package com.imooc.homeworktest;

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

public Weather() {

}

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 boolean isFlag() {
return flag;
}

public void setFlag(boolean flag) {
this.flag = flag;
}

@Override
public String toString() {
return "读取天气数据"+"Weather 温度" + temperature + ", 湿度" + humidity;
}

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

}
​package com.imooc.homeworktest;

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回答

好帮手慕小小

2021-08-15

同学你好,代码整体完成的不错,但还存在如下两个问题:

1、分支条件中应是判断flag的值为true或false,而不是为flag赋值,建议将“=”修改为“==”

2、读取结束后flag的值应为false,生成结束后flag的值应为true;

http://img.mukewang.com/climg/6118b3230981ebcf08070625.jpg

祝学习愉快~

0

0 学习 · 9886 问题

查看课程