银行账户模拟(线程协作) java 实现


public class bank {

/**
* @param args
*/
private account a = new account();
private withDraw with = new withDraw();
private depoit d = new depoit();
private withDraw w = new withDraw();
private depoit depot = new depoit();

bank(){
w.start();
depot.start();
}

public static void main(String[] args) {
bank b = new bank();// TODO Auto-generated method stub
}

class withDraw extends Thread {
public void run(){
while(true){
a.withDraw((int)(Math.random()*10)+1);

}
}
}

class depoit extends Thread {
public void run(){
while(true){
a.depoit((int)(Math.random()*10)+1);
try {
Thread.sleep(1000);
}catch(InterruptedException e){}
}
}
}

class account {
private int money = 0;
public int get(){
return money;
}
public synchronized void depoit(int moneyd){
money+=moneyd;
notifyAll();
System.out.println("depoit:"+moneyd+"还剩:"+a.get());
}
public synchronized void withDraw(int moneyw){
try {
while(money<moneyw)
wait();
}catch(InterruptedException w){}
money-=moneyw;
System.out.println("withDraw:"+moneyw+"还剩:"+a.get());

}
}
}

你可能感兴趣的:(java)