Java 多线程模拟天气数据读取

来源:互联网 发布:淘宝 店铺 推广 编辑:程序博客网 时间:2024/06/05 17:03
Javapublic 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();    }}
Javapublic 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();            }        }    }}
Javapublic 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();            }        }    }}
Javapublic class WeatherTest {    public static void main(String[] args) {        Weather weather = new Weather();        new Thread(new GenerateWeather(weather)).start();        new Thread(new ReadWeather(weather)).start();    }}

这里写图片描述

原创粉丝点击