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());
}
}
}
本文探讨了并发编程的核心概念,通过实现简单的银行账户模型,展示了如何使用线程进行存款和取款操作,并实现了线程同步和通信。重点介绍了同步机制、等待与通知机制以及线程之间的协作。
1625

被折叠的 条评论
为什么被折叠?



