代码是写出来了,但是如果老师不给需求分析,感觉就很僵硬,有点无从下手。
public class Weather {
/**
* 天气类Weather,包含int类型的温度(temperature)和湿度(humidity)属性
*/
private int temperature;
private int humidity;
private boolean flag=false;
//无参构造
public Weather() {}
//封装 仅限本类可以使用
private int getTemperature() {
return temperature;
}
private void setTemperature(int temperature) {
this.temperature = temperature;
}
private int getHumidity() {
return humidity;
}
private void setHumidity(int humidity) {
this.humidity = humidity;
}
//生成天气数据的方法,使用随机数获取0-40度之间的温度,0-100之间的湿度
public synchronized void generate() {
if(flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int tem=(int)(Math.random()*50-10);//气温设定为-10-40度之间。
this.setTemperature(tem);
if(tem>=20) {
this.setHumidity((int)(Math.random()*80+20));//当气温高于20度,湿度为20-100之间
}else {
this.setHumidity((int)(Math.random()*20));//当气温低于20度,湿度为之间0-20之间
}
System.out.println("生成天气数据"+this.toString());
flag=true;
notifyAll();//唤醒所有线程,防死锁!
}
//读取天气数据的方法
public synchronized void read() {
if(!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("读取天气数据"+this.toString());
flag=false;
notifyAll();//唤醒所有线程,防死锁!
}
//toString方法重写
@Override
public String toString() {
String str="[温度:" + this.getTemperature() + ", 湿度:" +this.getHumidity()+ "]";
return str;
}
}/**
* 生成天气数据线程
* @author Administrator
*
*/
public class GenerateWeather implements Runnable{
//定义Weather的对象
Weather weather=new Weather();
//无参构造
public GenerateWeather() {}
//有参构造
public GenerateWeather(Weather weather){
this.weather=weather;
}
@Override
public void run() {
while(true) {
weather.generate();
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}/**
* 读取天气数据
* @author Administrator
*
*/
public class ReaderWeather implements Runnable{
//定义Weather的对象
Weather weather=new Weather();
//无参构造
public ReaderWeather() {}
//有参构造
public ReaderWeather(Weather weather) {
this.weather=weather;
}
@Override
public void run() {
while(true) {
weather.read();
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}public class WeatherTest {
public static void main(String[] args) {
Weather weather=new Weather();
new Thread(new GenerateWeather(weather)).start();
new Thread(new ReaderWeather(weather)).start();
//启动生成/读取天气数据的线程!分开写的内容参考
// GenerateWeather gw=new GenerateWeather(weather);
// ReaderWeather rw=new ReaderWeather(weather);
// Thread th1=new Thread(gw);
// Thread th2=new Thread(rw);
// th1.start();
// th2.start();
}
}3
收起
正在回答
1回答
同学你好,1、贴出代码的实现效果没有问题,只是需要注意一下题目要求,比如:模拟生成100次天气数据,每次生成天气数据需要5秒的时间等等!
2、现在基础阶段就是要同学多练习代码,熟悉代码的编写过程哦!觉得无从下手,还是对代码不熟悉哟,要多加练习~
如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星