public class AccountDrawThread extends Thread {
private Account account;
private Integer drawBalance;
public AccountDrawThread(Account account, Integer drawBalance) {
this.account = account;
this.drawBalance = drawBalance;
}
public synchronized void draw() {
if(drawBalance > account.getBalance()) {
System.err.println("Not sufficient balance! 取款线程" + Thread.currentThread().getId());
} else
account.setBalance(account.getBalance()- drawBalance);
}
@Override
public void run() {
synchronized (account) {
Integer br = account.getBalance();
draw();
if(br == account.getBalance()) {
try {
account.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(" 取款线程" + Thread.currentThread().getId() + ": " + account.getBalance());
}
}
}
public class AccountDepositThread extends Thread {
private Account account;
private Integer depositBalance;
public AccountDepositThread(Account account, Integer depositBalance) {
this.account = account;
this.depositBalance = depositBalance;
// validation of account
}
public synchronized void deposit(Integer valu) {
account.setBalance(account.getBalance() + valu);
}
@Override
public void run() {
synchronized (account) {
deposit(depositBalance);
System.out.println("存款线程" + Thread.currentThread().getId() + ": " + account.getBalance());
if(account.getBalance() > 300) {
account.notifyAll();
}
}
}
}
public class BankAccountTest {
public static void main(String[] args) {
AccountDrawThread drawThread = null;
AccountDepositThread depositThread = null;
Account account = new Account(500);
for (int i = 0; i < 50; i++) {
depositThread = new AccountDepositThread(account, 200);
drawThread = new AccountDrawThread(account, 300);
depositThread.start();
drawThread.start();
}
}
}