Object vault;
public InPipe(Object vault){
this.vault=vault;
}
public void run(){
synchronized(vault){
System.out.println("Water filling");
try{
Thread.sleep(300000);
}
catch(InterruptedException e){}
System.out.println("Filling complete");
vault.notify();
try{
vault.wait();
}catch(InterruptedException e){}
}
}
}
class OutPipe extends Thread{
Object vault;
public OutPipe(Object vault){
this.vault=vault;
}
public void run(){
synchronized(vault){
System.out.println("Water emptying");
try{
Thread.sleep(180000);
}
catch(InterruptedException e){}
System.out.println("Emptying complete");
vault.notify();
try{
vault.wait();
}catch(InterruptedException e){}
}
}
}
public class WaterPool {
public static void main(String[] args){
Object vault=new Object();
InPipe ip=new InPipe(vault);
OutPipe op=new OutPipe(vault);
ip.start();
op.start();
}
}
大概是這樣,註水和排水交替進行。