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) {
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) {
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);
} catch (InterruptedException e) {
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);
} catch (InterruptedException e) {
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();
}
}