为什么不打印湿度温度呢
package com.wp.thread.weather;
public class Weather {
private int temperature; // 温度
private int humidity; // 湿度
boolean flag = false;
public Weather() {
}
public Weather(int temperature, int humidity) {
this.temperature = temperature;
this.humidity = humidity;
}
// 生成天气
public synchronized void generate() {
if (!flag) {
this.setTem((int) (Math.random() * 40));
this.setHum((int) (Math.random() * 100));
flag = true;
notifyAll();
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 读取天气
public synchronized void read() {
if (flag) {
System.out.println(this);
flag = false;
notifyAll();
} else {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// toString
public String toString() {
return "[温度:" + this.getTem() + ",湿度:" + this.getHum() + "]";
}
public void setTem(int tem) {
this.temperature = tem;
}
public void setHum(int hum) {
this.humidity = hum;
}
public int getTem() {
return this.temperature;
}
public int getHum() {
return this.humidity;
}
}
package com.wp.thread.weather;
public class GenerateWeather implements Runnable {
Weather one;
public GenerateWeather(Weather one) {
this.one = one;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
one.generate();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package com.wp.thread.weather;
public class ReadWeather implements Runnable{
Weather one;
public ReadWeather(Weather one) {
this.one = one;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
one.read();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package com.wp.thread.weather;
public class Test {
public static void main(String[] args) {
try {
new Thread(new GenerateWeather(new Weather())).join();
new Thread(new ReadWeather(new Weather())).join();
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new GenerateWeather(new Weather())).start();
new Thread(new ReadWeather(new Weather())).start();
}
}
正在回答 回答被采纳积分+1
找到原因了我把 测试类中的
new Thread(new GenerateWeather(new Weather())).start();
new Thread(new ReadWeather(new Weather())).start();
改成
Weather weather = new Weather();
new Thread(new GenerateWeather(weather)).start();
new Thread(new ReadWeather(weather)).start();
就ok了。虽然正常输出了,但是我还是不知道为什么会这样。不能这样创建对象吗?
你把!flag前面的叹号去掉试试,你对照这个https://class.imooc.com/course/qadetail/70262哥们的代码改一改,他的代码写的挺好的
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星