我检查了很多遍还是不知道为什么死锁
package com.imooc.weather;
public class Weather {
private int temperature;
private int humidity;
boolean flag=false;//数据为空
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() {
if(flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
this.setTemperature((int) (Math.random()*40));
this.setHumidity((int)(Math.random()*100));
System.out.println("生成天气数据[温度:"+this.getTemperature()+",湿度:"+this.getHumidity());
flag=true;
notifyAll();
}
}
public synchronized void read() {
if(!flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("读取天气数据[温度:"+this.getTemperature()+",湿度:"+this.getHumidity());
flag=false;
notifyAll();
}
}
public String toString() {
return "Weather[temperature="+this.getTemperature()+",湿度:"+this.getHumidity()+"]";
}
}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 自动生成的 catch 块
e.printStackTrace();
}
weather.generate();
}
}
}package com.imooc.weather;
public class ReadWeather implements Runnable{
Weather weather;
public ReadWeather(Weather weather){
this.weather=weather;
}
public void run() {
for(int i=1;i<=100;i++)
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
weather.read();
}
}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();
}
}17
收起
正在回答 回答被采纳积分+1
2回答
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程



如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星