正在回答 回答被采纳积分+1
3回答
holder姐
2020-05-21 11:43:20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | /** 不知一下思路是否正确,结果如图 设置了flag通信标识为数字,1是设置数据 2-读取数据,3-猜测数据, 是按设置-读取-猜测-设置-读取-猜测 这样依次获取资源的 然后增加了GuessWeather类,主方法启动了三个线程 new Thread(new GenerateWeather(weather)).start(); new Thread(new ReadWeather(weather)).start(); new Thread(new GuessWeather(weather)).start(); */ public class Weather { private int temp; //温度 private int hum; //湿度 private int flag = 1 ; //生成后才能读取 读取完才能继续下一次生成 1-生成 2-读取 3-猜测 public Weather() { } public int getTemp() { return temp; } public void setTemp( int temp) { this .temp = temp; } public int getHum() { return hum; } public void setHum( int hum) { this .hum = hum; } //生成天气 public synchronized void generate() { if (flag == 1 ) { notifyAll(); setTemp(( int ) (Math.random()* 40 )); setHum(( int ) (Math.random()* 100 )); System.out.println( "生成天气数据 [温度=" + temp + ", 湿度=" + hum + "]" ); flag = 2 ; } else { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //读取天气 public synchronized void read() { if (flag == 2 ) { notifyAll(); System.out.println( this .toString()); flag = 3 ; } else { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //猜测天气 public synchronized void guess() { if (flag == 3 ) { notifyAll(); System.out.println( "猜测天气数据 [温度=" + temp + ", 湿度=" + hum + "]" ); flag = 1 ; } else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } //读取天气信息 @Override public String toString() { return "读取天气数据 [温度=" + temp + ", 湿度=" + hum + "]" ; } } |
1.Android 零基础入门
- 参与学习 人
- 提交作业 1789 份
- 解答问题 2907 个
Android大楼Java起,本阶段是Android攻城狮培养计划的第一部分语法与界面基础篇,将带大家从0开始入门Android开发。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧