老是帮忙看一下代码有无问题

老是帮忙看一下代码有无问题

package cn.cdb.demo07;

import java.util.Random;

public class Weather {

    private int temperature;
    private int humidity;
    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) {
                e.printStackTrace();
            }
        }
        Random random = new Random();
        this.setTemperature(random.nextInt(40));
        this.setHumidity(random.nextInt(100));
        System.out.println("生成天气数据" + this.toString());
        flag = true;
        notifyAll();

    }

    public synchronized void read(){
        if(!flag){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("读取天气数据" + this.toString());
        flag = false;
        notifyAll();
    }

    @Override
    public String toString() {
        return "[" + "温度:" + this.getTemperature() + ",湿度:" + this.getHumidity() + "]";
    }
}
package cn.cdb.demo07;

public class GenerateWeather implements Runnable {

    Weather weather;
    int n = 1;
    public GenerateWeather(Weather weather2){
        this.weather = weather2;
    }

    @Override
    public void run() {

        while(true){

            weather.generate();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            n++;
            if(n==100){
                break;
            }
        }

    }

}
package cn.cdb.demo07;

public class ReadWeather implements Runnable {

    Weather weather;
    int n = 1;
    public ReadWeather(Weather weather) {
        this.weather = weather;
    }

    @Override
    public void run() {

        while (true) {

            this.weather.read();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            n++;
            if (n == 100) {
                break;
            }
        }

    }

}
package cn.cdb.demo07;

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();

    }


}


正在回答

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

1回答

练习完成的不错,加油,祝学习愉快~

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

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

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

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

在线咨询

领取优惠

免费试听

领取大纲

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