为什么wait(5000)放在if(flag)前面。就只执行一次啊。
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 | public class Weather { private int temperature; private int humidity; private boolean flag= false ; 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 synchronized void generate(){ if (flag){ try { wait(); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } //如果wait(5000)放在最前面。就只等一次。放在后面就是对的。表示不懂为毛。 try { wait( 5000 ); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } temperature=( int )(Math.random()* 41 ); humidity=( int )(Math.random()* 101 ); System.out.println( "生成天气数据" + this ); flag= true ; notifyAll(); } public synchronized void read(){ if (!flag){ try { wait(); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } try { wait( 100 ); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } System.out.println( "读取天气数据" + this ); flag= false ; notifyAll(); } @Override public String toString() { return " [温度:" + temperature + ", 湿度:" + humidity + "]" ; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class GenerateWeather implements Runnable { Weather weather; public GenerateWeather(Weather weather) { super (); this .weather = weather; } public void run() { // TODO 自动生成的方法存根 for ( int i= 0 ;i< 100 ;i++){ weather.generate(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class ReadWeather implements Runnable { Weather weather; public ReadWeather(Weather weather) { super (); this .weather = weather; } public void run() { // TODO 自动生成的方法存根 for ( int i= 0 ;i< 100 ;i++){ weather.read(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class WeatherTest { public static void main(String[] args) { // TODO 自动生成的方法存根 Weather weather= new Weather(); GenerateWeather generateWeather= new GenerateWeather(weather); new Thread(generateWeather).start(); ReadWeather readWeather= new ReadWeather(weather); new Thread(readWeather).start(); } } |
0
收起
正在回答 回答被采纳积分+1
3回答
Android零基础入门2018版
- 参与学习 人
- 提交作业 5461 份
- 解答问题 7235 个
此次推出的专题为Android攻城狮培养计划的第一部分语法与界面基础篇,将带大家从0开始学习Android开发。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧