Java线程练习5-3,烦请老师检查并指正~
天气类
package com.imooc.thread.exercise5_3;
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);
}
//getters/setters方法
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();
}
}
this.temperature = (int) (Math.random() * 40);
this.humidity = (int) (Math.random() * 100);
System.out.println("生成天气数据 [温度=" + this.getTemperature() + ", 湿度=" + this.getHumidity() + "]");
flag = true;
notifyAll();
}
//读取数据的方法
public synchronized void read() {
//有数据的情况下可读取数据
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("读取天气数据 [温度=" + this.getTemperature() + ", 湿度=" + this.getHumidity() + "]");
flag = false;
notifyAll();
相关代码:}
//重写tostring方法
@Override
public String toString() {
return "[温度=" + temperature + ", 湿度=" + humidity + "]";
}
}
产生天气类
package com.imooc.thread.exercise5_3;
public class GenerateWeather implements Runnable {
//成员属性:对象
private Weather weather;
//无参构造方法
public GenerateWeather() {
}
//有参构造方法
public GenerateWeather(Weather weather) {
this.setWeather(weather);
}
//getters/setters方法
public Weather getWeather() {
return weather;
}
public void setWeather(Weather weather) {
this.weather = weather;
}
//重写结构的run方法
@Override
public void run() {
for (int i = 0; i < 100; i++) {
weather.generate();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
读取天气类
package com.imooc.thread.exercise5_3;
public class ReadWeather implements Runnable {
//成员属性:对象
private Weather weather;
//无参构造方法
public ReadWeather() {
}
//有参构造方法
public ReadWeather(Weather weather) {
this.setWeather(weather);
}
//getters/setters方法
public Weather getWeather() {
return weather;
}
public void setWeather(Weather weather) {
this.weather = weather;
}
//重写结构的run方法
@Override
public void run() {
for (int i = 0; i < 100; i++) {
weather.read();
try {
Thread.currentThread().join(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类
package com.imooc.thread.exercise5_3;
public class WeatherTest {
public static void main(String args[]) {
Weather w = new Weather();
Thread td = new Thread(new GenerateWeather(w));
td.start();
Thread td1 = new Thread(new ReadWeather(w));
td1.start();
}
}
18
收起
正在回答
1回答
同学你好,已完成练习,代码实现符合题目要求,逻辑清晰,继续加油!
祝学习愉快~
2023版Java工程师
- 参与学习 人
- 提交作业 8792 份
- 解答问题 9886 个
综合就业常年第一,编程排行常年霸榜,北上广深月薪过万! 不需要基础,无需脱产即可学习,只要你有梦想,想高薪! 全新升级:技术栈升级(包含VUE3.0,ES6,Git)+项目升级(前后端联调与功能升级)
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星