public class Deposit {
public static void main(String[] args) {
BankAccount ba=new BankAccount();
ThreadGroup tg=new ThreadGroup("BankClient Group");
for (int i = 0; i < 5; i++) {
Thread t=new Thread(tg,new BankClient(ba));
t.start();
}
while (tg.activeCount()!=0){
}
System.out.println("BankAccount balance is:"+ba.getBalance());
}
}
class BankAccount{
private int balance;
BankAccount(){
balance=0;
}
int getBalance(){
return balance;
}
synchronized void add(){
int newBalance=balance+1000;
try{
Thread.sleep(1);
}catch (InterruptedException e){
System.out.println(e);
}
balance=newBalance;
}
}
class BankClient extends Thread{
BankAccount ba;
BankClient(BankAccount ba){
this.ba=ba;
}
public void run(){
ba.add();
}
}
模拟银行交易(使用线程同步)程序
最新推荐文章于 2024-08-14 23:12:09 发布