Java 多線程模擬天氣數據讀取

Java
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) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        this.setTemperature((int) (Math.random() * 100));
        this.setHumidity((int) (Math.random() * 40));
        System.out.println("生成天氣數據[溫度:" + this.getTemperature() + ",溼度" + this.getHumidity() + "]");
        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.getTemperature() + ",溼度" + this.getHumidity() + "]");
        flag = false;//表示用掉了數據
        notifyAll();
    }

}
Java
public class GenerateWeather implements Runnable { // 生成數據的線程類
    Weather weather;

    GenerateWeather(Weather weather) {
        this.weather = weather;
    }

    @Override
    public void run() {
        while (true) {
            weather.generate();// 調用生成方法
            try {
                Thread.sleep(5000);// 睡眠5秒
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
Java
public class ReadWeather implements Runnable{ //讀取數據線程類
    Weather weather;
    ReadWeather(Weather weather){
        this.weather = weather;
    }
    @Override
    public void run() {
        while(true){
            weather.read();//調用讀取方法
            try {
                Thread.sleep(100);//睡眠0.1秒
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

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

    }

}

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章