运行时直接生成两个天气数据?
老师,我的代码在运行时会直接生成两个天气数据,后面才一次依据5S的频率生成。代码如下
package com.imooc.weather;
import java.util.Random;
public class Weather {
private int tep;
private int hum;
boolean flag=false;
public int getTep() {
return tep;
}
public void setTep(int tep) {
this.tep = tep;
}
public int getHum() {
return hum;
}
public void setHum(int hum) {
this.hum = hum;
}
//生成天气数据的方法
public synchronized void generate() {
//调用一个生成随机数的方法,随机生产温度和湿度
if(flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Random t=new Random();
tep=t.nextInt(40);
this.setTep(tep);
hum=t.nextInt(101);
this.setHum(hum);
System.out.println("生成天气数据"+toString());
flag=true;
notifyAll();
}
//读取天气数据的方法
public synchronized void read() {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("读取天气数据"+toString());
flag=false;
notifyAll();
}
//重写toString方法
@Override
public String toString() {
return " [温度:" + tep + ", 湿度:" + hum + "]";
}
}
package com.imooc.weather;
public class GenerateWeather implements Runnable {
Weather weather;
public GenerateWeather() {
}
public GenerateWeather(Weather weather) {
this.weather=weather;
weather.generate();
}
@Override
public void run() {
for(int i=1;i<100;i++) {
weather.generate();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package com.imooc.weather;
public class ReadWeather implements Runnable {
Weather weather;
public ReadWeather() {
}
public ReadWeather(Weather weather) {
this.weather=weather;
weather.read();
}
@Override
public void run() {
for(int i=1;i<100;i++) {
weather.read();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
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);
new Thread(g).start();
new Thread(r).start();
}
}
正在回答
同学你好,这里之所以刚开始运行就弹出四条信息是因为:GenerateWeather和ReadWeather类中的有参构造方法中调用generate()方法和read()方法。导致打印语句执行了两次。修改如下:
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
- 参与学习 人
- 提交作业 9393 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星