1、 天气类Weather,包含int类型的温度(temperature)和湿度(humidity)属性,以及布尔类型的属性flag用于判断是生成还是读取天气信息。
方法包括:
(1) 温度和湿度属性的getter和setter方法
(2) 生成天气数据的方法public void generate()
使用随机数获取0-40度之间的温度,0-100之间的湿度
(3) 读取天气数据的方法public void read()
(4) 重写toString()方法
2、 生成天气线程类GenerateWeather
属性为Weather类的对象,包括构造方法和run方法。
3、 读取天气线程类ReadWeather
属性为Weather类的对象,包括构造方法和run方法。
4、 测试类WeatherTest
在主方法中模拟生成和读取数据的过程
package Weather;
public class Weather {
private int temp;
private int wet;
boolean flag=false;
public synchronized void setTemp(int temp) { //synchronized 是这个方法运行完之前线程不会去运行其他
if (flag==false){
try {
wait(); // 让线程处于停滞状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}
flag=false;
notifyAll(); // 激活线程
this.temp = temp;
}
public synchronized void setWet(int wet) {
if (flag==false){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
flag=false;
notifyAll();
this.wet = wet;
}
public synchronized int getWet() {
if (flag==true){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
flag=true;
notifyAll();
return wet;
}
public synchronized int getTemp() {
if (flag==true){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
flag=true;
notifyAll();
return temp;
}
@Override
public String toString() {
return "温度"+temp+"湿度"+wet;
}
}
package Weather;
public class ReadWeather implements Runnable{
Weather weather;
ReadWeather(Weather weather){
this.weather=weather;
}
@Override
public void run() {
for (int i=0;i<100;i++){
weather.getWet();
weather.getTemp();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("读取天气数据"+weather);
}
}
}
package Weather;
public class GenerateWeather implements Runnable {
Weather weather;
GenerateWeather (Weather weather){
this.weather=weather;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
weather.setWet(i);
weather.setTemp(i+1);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("产生天气数据"+weather);
}
}
}
package Weather;
public class WeatherTest {
public static void main(String[] args) {
Weather weather = new Weather();
new Thread(new ReadWeather(weather)).start();
new Thread(new GenerateWeather(weather)).start();
}
}