请老师帮忙解决一下,这样编码是否合理,谢谢:
第一个类:----------------------------------------
package com.misi.imooc.tools.thread.work6;
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(int a, int b) {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setTemperature(a);
this.setHumidity(b);
System.out.println("生成:[温度:" + a + ",湿度:" + b + "]");
flag = true;
notifyAll();
}
public synchronized void read() {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("获取:[温度:" + getTemperature() + ",湿度:"
+ getHumidity() + "]");
flag = false;
notifyAll();
}
@Override
public String toString() {
return "[温度:" + getTemperature() + ",湿度:" + getHumidity() + "]";
}
}
第二个类:---------------------------------
package com.misi.imooc.tools.thread.work6;
public class GenerateWeather implements Runnable {
Weather weather;
public GenerateWeather(Weather weather) {
super();
this.weather = weather;
}
public GenerateWeather() {
super();
}
public void run() {
while (true) {
int a = (int) (Math.round(Math.random() * 40));
int b = (int) (Math.round(Math.random() * 100));
weather.generate(a, b);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
第三个类:----------------------------------------------
package com.misi.imooc.tools.thread.work6;
public class ReadWeather implements Runnable {
Weather weather;
public ReadWeather(Weather weather) {
super();
this.weather = weather;
}
public ReadWeather() {
super();
}
public void run() {
while (true) {
weather.read();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类:-----------------------------------
package com.misi.imooc.tools.thread.work6;
public class Test {
public static void main(String[] args) {
Weather we=new Weather();
new Thread(new GenerateWeather(we)).start();
new Thread(new ReadWeather(we)).start();
}
}
正在回答 回答被采纳积分+1
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星