class Bank{
public static int fund=0;
boolean bfull=false;
public synchronized void saveMoney(){
if(bfull==true)
try{wait();}catch(Exception e){}
fund=fund+100;
System.out.println(fund);
bfull=true;
try{notify();}catch(Exception e){}
}
public synchronized void takeMoney(){
if(bfull==false)
try{wait();}catch(Exception e){}
fund=fund-100;
System.out.println(fund);
bfull=false;
try{notify();}catch(Exception e){}
}
}
class Dad implements Runnable{
Bank b=null;
public Dad(Bank b){
this.b=b;
}
public void run(){
while(true){
b.saveMoney();
}
}
}
class Son implements Runnable{
Bank b=null;
public Son(Bank b){
this.b=b;
}
public void run(){
while(true){
b.takeMoney();
}
}
}
class Test{
public static void main(String args[]){
Bank b=new Bank();
Thread t1=new Thread(new Dad(b));
Thread t2=new Thread(new Son(b));
t1.start();
t2.start();
}
}
转载于:https://my.oschina.net/crooner/blog/655968