5-3 自由编程题请老师点评
//Weather类
public class Weather {
static int temperature;
static int humidity;
// 输入两个值,需要两个布尔型变量控制
static boolean flag1 = false;
static boolean flag2 = false;
public synchronized int getTemperature() {
return temperature;
}
public synchronized int getHumidity() {
return humidity;
}
public synchronized void setValue(int temperature, int humidity) {
this.humidity = humidity;
this.temperature = temperature;
// 两个属性已经赋值
}
// 生成天气数据的方法
public synchronized void generate() {
// 使用随机数获取0-40度之间的温度,0-100之间的湿度
if (flag1) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
setValue((int) (1 + Math.random() * 40), (int) (1 + Math.random() * 100));
System.out.println("生成" + new Weather());
flag1 = true;
}
// 读取天气数据的方法
public synchronized void read() {
if (!flag1) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("获取" + new Weather());
flag1 = false;
}
// 重写toString方法
@Override
public String toString() {
return "天气数据 [温度:" + temperature + ", 湿度:" + humidity + "]";
}
}
//生产天气数据线程类
public class GenerateWeather implements Runnable {
// 定义Weather对象
Weather weather;
// 构造方法
public GenerateWeather(Weather weather) {
this.weather = weather;
}
public GenerateWeather() {
// TODO Auto-generated constructor stub
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
weather.generate();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//读取天气数据线程类
public class ReadWeather implements Runnable {
// 定义Weather对象
Weather weather;
public ReadWeather(Weather weather) {
this.weather = weather;
}
public Weather getWeather() {
return weather;
}
public void setWeather(Weather weather) {
this.weather = weather;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 1; i < 100; i++) {
weather.read();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//天气测试类
public class WeatherTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Weather weather = new Weather();
new Thread(new GenerateWeather(weather)).start();
new Thread(new ReadWeather(weather)).start();
}
}
正在回答
基本上没什么问题,加油,祝学习愉快~
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星