package myproject;
class Pool{
int volume=20;
boolean flag=false;
}
class Enter extends Thread{
Pool p;
public Enter(Pool p){
this.p=p;
}
@Override
public void run() {
int i=0;
while(true){
synchronized (p) {
if(p.flag){
if(i<=p.volume){
System.out.println("水池的水已有"+i);
i+=5;
}else{
System.out.println("水池已经注满");
p.flag=false;
p.notifyAll();
}
}else{
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
class Exit extends Thread{
Pool p;
public Exit(Pool p){
this.p=p;
}
public void run(){
int i=p.volume;
while(true){
if(!p.flag){
synchronized (p) {
if(i>=0){
System.out.println("水池已经放掉了"+i);
i-=2;
}else{
System.out.println("水池已经放空了...");
p.flag=true;
p.notifyAll();
}
}
}else{
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class Test{
public static void main(String[] args) {
Pool p=new Pool();
Enter enter=new Enter(p);
Exit exit=new Exit(p);
exit.start();
enter.start();
}
} |
|