1  import java.util.concurrent.locks.Condition;
  2  import java.util.concurrent.locks.Lock;
  3  import java.util.concurrent.locks.ReentrantLock;
  4  
  5  /**
  6     A bank account has a balance that can be changed by 
  7     deposits and withdrawals.
  8  */
  9  public class BankAccount
 10  {
 11     private double balance;
 12     private Lock balanceChangeLock;
 13     private Condition sufficientFundsCondition;
 14  
 15     /**
 16        Constructs a bank account with a zero balance.
 17     */
 18     public BankAccount()
 19     {
 20        balance = 0;
 21        balanceChangeLock = new ReentrantLock();
 22        sufficientFundsCondition = balanceChangeLock.newCondition();
 23     }
 24  
 25     /**
 26        Deposits money into the bank account.
 27        @param amount the amount to deposit
 28     */
 29     public void deposit(double amount)
 30     {
 31        balanceChangeLock.lock();
 32        try
 33        {
 34           System.out.print("Depositing " + amount);
 35           double newBalance = balance + amount;
 36           System.out.println(", new balance is " + newBalance);
 37           balance = newBalance;
 38           sufficientFundsCondition.signalAll();
 39        }
 40        finally
 41        {
 42           balanceChangeLock.unlock();
 43        }
 44     }
 45     
 46     /**
 47        Withdraws money from the bank account.
 48        @param amount the amount to withdraw
 49     */
 50     public void withdraw(double amount)
 51           throws InterruptedException
 52     {
 53        balanceChangeLock.lock();
 54        try
 55        {
 56           while (balance < amount)
 57           {
 58              sufficientFundsCondition.await();
 59           }
 60           System.out.print("Withdrawing " + amount);
 61           double newBalance = balance - amount;
 62           System.out.println(", new balance is " + newBalance);
 63           balance = newBalance;
 64        }
 65        finally
 66        {
 67           balanceChangeLock.unlock();
 68        }
 69     }
 70     
 71     /**
 72        Gets the current balance of the bank account.
 73        @return the current balance
 74     */
 75     public double getBalance()
 76     {
 77        return balance;
 78     }
 79  }