老师检查代码

来源:5-3 自由编程

热爱编程学习

2022-04-01 08:53:47

public class Weather {
    private int temperature;
    private int humidity;
    private boolean fast=false;

    public  Weather(){}

    public Weather(int temperature,int humidity){
        this.setTemperature(temperature);
        this.setHumidity(humidity);

    }

    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;
    }

    @Override
    public String toString() {
        return "天气读取{" +
                "温度=" + temperature +
                ", 湿度=" + humidity +
                '}';
    }

    public synchronized void generate(){
        int i,y;
        if(fast){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        i=(int)(Math.random()*40);
        y=(int)(Math.random()*100);
        this.setTemperature(i);
        this.setHumidity(y);
        System.out.println("生成天气"+"温度"+i+"湿度"+y);
        fast=true;
        notifyAll();
    }

    public synchronized void read(){
        if(!fast){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(this.toString());
        fast=false;
        notifyAll();
    }


}

public class WeatherTest {
    public static void main(String[] args) {
        Weather w=new Weather();
        GenerateWeather gw=new GenerateWeather(w);
        ReadWeather rw=new ReadWeather(w);
        Thread t1=new Thread(gw);
        Thread t2=new Thread(rw);
        t1.start();
        t2.start();
    }
}


public class GenerateWeather implements Runnable{
    Weather weather;
    public GenerateWeather( Weather weather){
        this.weather=weather;
    }
    @Override
    public void run() {
        for (int i=0;i<=20;i++){
            weather.generate();
        }
    }
}

public class ReadWeather implements Runnable{
    Weather weather;
    public ReadWeather(Weather weather){
        this.weather=weather;
    }
    @Override
    public void run() {
        for (int i=0;i<=20;i++){
            weather.read();
        }
    }
}


写回答

1回答

好帮手慕小脸

2022-04-01

同学你好,测试运行上述贴出代码是可以的,棒棒的~但为了更贴合作业需求,同学可以为生成天气数据以及读取数据设置秒数

https://img.mukewang.com/climg/62466b2009ca2ae208660164.jpg

https://img.mukewang.com/climg/62466b74092dc90705570268.jpg

https://img.mukewang.com/climg/62466b80091a353804680186.jpg

祝学习愉快~


0

0 学习 · 9886 问题

查看课程