写出来好像没什么问题,可是感觉做起来思路很乱

写出来好像没什么问题,可是感觉做起来思路很乱

package com.imooc.weather;


import java.util.Random;


public class Weather {

private int temperature;

private int humidity;

boolean flag = false;


public Weather() {


}


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 Auto-generated catch block

e.printStackTrace();

}

}

Random r = new Random();

int a = r.nextInt(41);

int b = r.nextInt(101);

this.temperature = a;

this.humidity = b;

System.out.println("生成" + this);

flag = true;

notifyAll();

}


public synchronized void read() {

if (!flag) {

try {

wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

System.out.println("读取" + this);

flag = false;

notifyAll();

}


public String toString() {

return "天气数据[温度:" + this.temperature + ",湿度:" + this.humidity + "]";

}

}



package com.imooc.weather;


public class GenerateWeather implements Runnable {

Weather weather;


public GenerateWeather(Weather weather) {

this.weather = weather;

}


@Override

public void run() {

for (int i = 1; i <= 100; i++) {

weather.generate();

try {

Thread.sleep(5000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}



package com.imooc.weather;


public class ReadWeather implements Runnable {

Weather weather;


public ReadWeather(Weather weather) {

this.weather = weather;

}


@Override

public void run() {

for (int i = 1; i <= 100; i++) {

weather.read();

try {

Thread.sleep(100);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}



package com.imooc.weather;


public class TestWeather {


public static void main(String[] args) {

// TODO Auto-generated method stub

Weather w = new Weather();

GenerateWeather g = new GenerateWeather(w);

ReadWeather r = new ReadWeather(w);

Thread a = new Thread(g);

Thread b = new Thread(r);

a.start();

b.start();


}


}


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕小尤 2019-12-18 19:03:32

同学你好,同学已完成练习,棒棒哒!同学既然可以实现代码代表同学思路是正确的,可以重新在整理一下思路。如果同学还是感觉有部分思路乱的话,同学可以反馈上来。

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师