线程出现死锁问题,设置同步,wait()方法感觉没起作用,麻烦老师指点一下
# 具体遇到的问题
# 报错信息的截图
# 相关课程内容截图
# 尝试过的解决思路和结果
# 粘贴全部相关代码,切记添加代码注释(请勿截图)
在这里输入代码,可通过选择
package com.imooc.weather;
public class Weather {
private int temperature;
private int humidity;
boolean flag = false;
public Weather() {
}
public Weather(int temperature, int humidity ) {
this.setTemperature(temperature);
this.setHumidity(humidity);
}
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) {
e.printStackTrace();
}
}
temperature = (int) (Math.random() * 40);// 随机获取0-40的温度
humidity = (int) (Math.random() * 100);// 随机获取0-100的湿度
System.out.println("生成天气数据:" + this.toString());
flag = true;// 数据生成完毕,等待读取
notifyAll();
}
public synchronized void read() {// 读取天气的方法
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("读取天气数据:" + this.toString());
flag = false;// 数据已读取,等待新数据
notifyAll();
}
// toString
@Override
public String toString() {
return "[温度=" + this.temperature + ", 湿度=" + this.humidity + "]";
}
}
【代码语言】突出显示
package com.imooc.weather;
public class GenerateWeather implements Runnable{
Weather weather1;
public GenerateWeather(Weather weather1) {
this.weather1=weather1;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<100;i++) {
weather1.generate();
try {
Thread.sleep(5000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.imooc.weather;
public class ReadWeather implements Runnable {
Weather weather2;
public ReadWeather(Weather weather2) {
this.weather2=weather2;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<=100;i++){}
weather2.read();
System.out.println(weather2.toString());
try {
Thread.sleep(100);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
package com.imooc.weather;
public class WeatherTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Weather we=new Weather();
new Thread(new GenerateWeather(we)).start();
new Thread(new ReadWeather(we)).start();
}
}
正在回答 回答被采纳积分+1
- 参与学习 人
- 提交作业 1789 份
- 解答问题 2907 个
Android大楼Java起,本阶段是Android攻城狮培养计划的第一部分语法与界面基础篇,将带大家从0开始入门Android开发。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星