5-3自由编程,请老师看看我的问题
package thread;
//Weather类
public class Weather {
private int temperature;
private int humidity;
boolean flag=false;
public Weather() {
}
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;
}
@Override
public String toString() {
return "天气数据 [温度:" + temperature + ", 湿度:" + humidity + "]";
}
public synchronized void generate() {
for(int i=0;i<100;i++) {
int n=(int)(Math.random()*40);
int m=(int)(Math.random()*100);
setTemperature(n);
setHumidity(m);
if(flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notifyAll();
System.out.println("生成"+toString());
flag=true;
}
}
public synchronized void read() {
for(int i=0;i<100;i++) {
this.temperature=getTemperature();
this.humidity=getHumidity();
if(!flag) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("读取"+toString());
flag=false;
}
}
}
//GenerateWeather类
package thread;
public class GenerateWeather implements Runnable {
Weather weather;
public GenerateWeather(Weather weather) {
// TODO Auto-generated constructor stub
this.weather=weather;
}
@Override
public void run() {
// TODO Auto-generated method stub
weather.generate();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// ReadWeather类
package thread;
public class ReadWeather implements Runnable{
Weather weather;
public ReadWeather(Weather weather) {
// TODO Auto-generated constructor stub
this.weather=weather;
}
@Override
public void run() {
// TODO Auto-generated method stub
weather.read();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//主类
package thread;
public class WeatherTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Weather weather=new Weather();
try {
new Thread(new GenerateWeather(weather)).join();
new Thread(new ReadWeather(weather)).join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread(new GenerateWeather(weather)).start();
new Thread(new ReadWeather(weather)).start();
}
}0
收起
正在回答 回答被采纳积分+1
3回答
慕前端6228120
2018-09-28 21:05:35
慕前端6228120
2018-09-28 18:50:28
生成天气数据 [温度:15, 湿度:38]
读取天气数据 [温度:15, 湿度:38]
生成天气数据 [温度:4, 湿度:52]
读取天气数据 [温度:34, 湿度:79]
生成天气数据 [温度:34, 湿度:79]
读取天气数据 [温度:25, 湿度:75]
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程




恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星