练习打卡,请老师检查~
package com.imooc.exercise_5_3; import java.util.Random; public class Weather { // 包含int类型的温度(temperature)和湿度(humidity)属性,以及布尔类型的属性flag private int temperature; private int humidity; boolean flag = false; // 构造方法 public Weather() { this(0,0); } public Weather(int temperature, int humidity) { this.setTemperature(temperature); this.setHumidity(humidity); } // 温度和湿度属性的getter和setter方法 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; } // 生成天气数据的方法public void generate() public synchronized void generate() { if (flag) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.setTemperature((int) (Math.random() * 40)); this.setHumidity((int) (Math.random() * 100)); System.out.println("生成天气数据:" + this.toString()); flag = true; // 生成完毕,容器有数据 notifyAll(); } // 读取天气数据的方法public void read() 读取天气数据 public synchronized void read() { if (!flag) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("读取天气数据:" + toString()); flag = false;// 读取完毕,容器已经没有数据 notifyAll(); } // 重写toString()方法 @Override public String toString() { return "[温度:" + this.getTemperature() + ", 湿度:" + this.getHumidity() + "]"; } } package com.imooc.exercise_5_3; public class GenerateWeather implements Runnable { Weather weather; GenerateWeather(Weather weather) { this.weather = weather; } @Override public void run() { int i = 0; while (i <= 100) { weather.generate(); i++; } try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } package com.imooc.exercise_5_3; public class ReadWeather implements Runnable { Weather weather; ReadWeather(Weather weather) { this.weather = weather; } @Override public void run() { int i = 0; while (i <= 100) { weather.read(); i++; } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } package com.imooc.exercise_5_3; public class WeatherTest { public static void main(String[] args) { Weather weather = new Weather(); new Thread(new GenerateWeather(weather)).start(); new Thread(new ReadWeather(weather)).start(); } }
21
收起
正在回答
1回答
同学你好,按照练习需求建议同学在生成天气数据睡眠5秒的时间,在读取数据睡眠0.1秒的时间。建议在循环中调用sleep()方法。修改后代码如下所示:
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
java工程师2020版
- 参与学习 人
- 提交作业 9401 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星