需求分析:
1、设计一个天气类Weather,用于温度和湿度数据的存放和读取。
2、设计一个线程类GenerateWeather,用于生成天气数据,模拟生成100次天气数据,每次生成天气数据需要5秒的时间。
3、设计一个线程类ReadWeather,用于读取天气数据,模拟读取100次天气数据,每次读取数据需要0.1秒的时间。
4、设计一个测试类WeatherTest,模拟生成和读取数据的过程,要求实现生成一次,紧接着进行读取,不能出现不同步的情况。
1.天气类
package com.imooc.weather;
public class Weather {
private int wd;//温度
private int sd;//湿度
boolean flag=false;
public int getWd() {
return wd;
}
public void setWd(int wd) {
this.wd = wd;
}
public int getSd() {
return sd;
}
public void setSd(int sd) {
this.sd = sd;
}
//生成温度和湿度
public synchronized void generateWeather() {
int wd=getWd();
int sd=getSd();
int max1=40,min1=-10;//温度设置为-10℃-40℃
int max2=70,min2=20;//湿度设置为20-70
if(!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
wd