Java线程练习5-3,烦请老师检查并指正~

来源:5-3 自由编程

Heijyu

2021-10-09 10:25:12

天气类
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();

}

}
写回答

1回答

好帮手慕小小

2021-10-09

同学你好,已完成练习,代码实现符合题目要求,逻辑清晰,继续加油!

祝学习愉快~

1

0 学习 · 9886 问题

查看课程