老师好~帮忙检查一下作业
public class Weather {
private int temperature;
private int humidity;
boolean flag = false;
public Weather() {
super();
}
public Weather(int departure, int humidity) {
super();
this.temperature = departure;
this.humidity = humidity;
}
public int getDeparture() {
return temperature;
}
public void setDeparture(int departure) {
this.temperature = departure;
}
public int getHumidity() {
return humidity;
}
public void setHumidity(int humidity) {
this.humidity = humidity;
}
public synchronized void read() {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
this.getDeparture();
this.getHumidity();
flag = false;
System.out.println("读取天气数据" + this.toString());
notifyAll();
}
public synchronized void generate() {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
this.setDeparture((int) ((Math.random()) * 40));
this.setHumidity((int) ((Math.random()) * 100));
flag = true;
System.out.println("生成天气数据" + this.toString());
notifyAll();
}
@Override
public String toString() {
return "[温度:" + this.getDeparture() + ", 湿度:" + this.getHumidity() + "]";
}
}
public class GenerateWeather implements Runnable {
Weather w ;
public GenerateWeather(Weather w) {
super();
this.w = w;
}
@Override
public void run() {
// TODO 自动生成的方法存根
for(int i =0;i<100;i++) {
w.generate();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
public class ReadWeather implements Runnable {
Weather w;
public ReadWeather(Weather w) {
super();
this.w = w;
}
@Override
public void run() {
// TODO 自动生成的方法存根
for (int i = 0; i < 100; i++) {
w.read();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
public class WeatherTest {
public static void main(String[] args) {
Weather w = new Weather();
GenerateWeather g = new GenerateWeather(w);
ReadWeather r = new ReadWeather(w);
Thread i1 = new Thread(g);
Thread i2 = new Thread(r);
i1.start();
i2.start();
}
}正在回答
同学你好,代码完成的不错!继续努力!
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题
登录后可查看更多问答,登录/注册
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星