老师,这个代码被我改了,跑不到20个呢?
package com.imooc.weather;
public class WeatherTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Weather w=new Weather();
GenerateWeather g=new GenerateWeather(w);
ReadWeather r=new ReadWeather(w);
Thread t1=new Thread(g);
Thread t2=new Thread(r);
t1.start();
t2.start();
}
}
package com.imooc.weather;
public class Weather {
private int temperature;
private int humidity;
private boolean flag=false;
public Weather() {}
public Weather(int temperature, int humidity,boolean flag) {
super();
this.temperature = temperature;
this.humidity = humidity;
this.flag = flag;
}
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 synchronized void generate() {
int n=0,y=0;
if(!flag) {
n=(int)(Math.random()*40);
setTemperature(n);
y=(int)(Math.random()*100);
setHumidity(y);
System.out.println("生成"+n+"天气"+y+"温度");
flag=true;
}else {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notifyAll();
}
public synchronized void read() {
if(flag) {
System.out.println("读取"+getTemperature()+"天气"+getHumidity()+"温度");
flag=false;
}else {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notifyAll();
//System.out.println("读取"+getTemperature()+"天气"+getHumidity()+"温度");
//getTemperature();
//getHumidity();
}
@Override
public String toString() {
return "温度: " + temperature + "湿度:" + humidity;
}
}
package com.imooc.weather;
public class ReadWeather implements Runnable{
Weather weather;
public ReadWeather(Weather weather) {
super();
this.weather = weather;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<=20;i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
weather.read();
}
}
}
package com.imooc.weather;
public class GenerateWeather implements Runnable{
Weather weather;
public GenerateWeather(Weather weather) {
super();
this.weather = weather;
}
@Override
public void run() {
// TODO Auto-generated method stub
// int n=0 ,y=0;
for(int i=0;i<=20;i++) {
// n=(int)(Math.random()*40);
// weather.setTemperature(n);
// y=(int)(Math.random()*100);
// weather.setHumidity(y);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
weather.generate();
}
}
}9
收起
正在回答
1回答
同学你好,老师这里测试同学的代码,有可能在最后一对数据输出之后,再输出一次生成的数据,但是没有对应的读取数据。
出现这个问题的原因是同学的flag改变代码写在了if结构中,这样当第一次执行时如果是read线程,那么这次是什么都没做然后进入循环的下一次,相当于消耗了一次读取的机会,就会导致无法成对出现。
祝学习愉快~
2023版Java工程师
- 参与学习 人
- 提交作业 8790 份
- 解答问题 9886 个
综合就业常年第一,编程排行常年霸榜,北上广深月薪过万! 不需要基础,无需脱产即可学习,只要你有梦想,想高薪! 全新升级:技术栈升级(包含VUE3.0,ES6,Git)+项目升级(前后端联调与功能升级)
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星