下面是源代码
package per.llldf.lx;
public class Weather {
private int humidity;
private int temperature;
boolean flag = false;
public Weather() {
}
public int getHumidity() {
return humidity;
}
public void setHumidity(int humidity) {
this.humidity = humidity;
}
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
@Override
public String toString() {
return " [湿度:" + humidity + ", 温度:" + temperature + "]";
}
public synchronized void get() {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}}
System.out.println("获取的天气:" + this);
flag = false;
notifyAll();
}
public synchronized void gene() {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}}
this.setHumidity(((int)(Math.random() * 101)));
this.setTemperature(((int)(Math.random() * 41)));
System.out.println("生成的天气:" + this);
flag = true;
notifyAll();
}
}
package per.llldf.lx;
public class Gene implements Runnable{
Weather w;
Gene(Weather w){
this.w = w;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
w.gene();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
}
package per.llldf.lx;
public class Read implements Runnable{
Weather w;
Read(Weather w){
this.w = w;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 100; i++) {
w.get();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
}
package per.llldf.lx;
public class Test {
public static void main(String[] args) {
Weather w = new Weather();
new Thread(new Gene(w)).start();
new Thread(new Read(w)).start();
}
}