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              sufficientFundsCondition.await();
 58           System.out.print("Withdrawing " + amount);
 59           double newBalance = balance - amount;
 60           System.out.println(", new balance is " + newBalance);
 61           balance = newBalance;
 62        }
 63        finally
 64        {
 65           balanceChangeLock.unlock();
 66        }
 67     }
 68     
 69     /**
 70        Gets the current balance of the bank account.
 71        @return the current balance
 72     */
 73     public double getBalance()
 74     {
 75        return balance;
 76     }
 77  }