import java.util.ArrayList; public class Account { // The current balance in the account. private int balance = 200; // Protected by lock on "this" private ArrayList listeners = new ArrayList(); /** * Withdraw money from an account. If this would bring the balance below 0, wait * for a deposit to occur * @param amount the amount to withdraw * @throws InterruptedException thrown if the thread is interrupted while it is waiting * for a deposit. */ public synchronized void withdraw (int amount) throws InterruptedException { // What would the new balance be? int newBalance = balance - amount; // Wait until the new balance would be positive while (newBalance < 0) { System.out.println("waiting"); // Wait for a deposit wait(); System.out.println("awakened"); // Check what the new balance would now be newBalance = balance - amount; } // Update the balance balance = newBalance; System.out.println(balance); // Update the display notifyListeners(); } /** * Deposit money into the account * @param amount the amount to deposit */ public synchronized void deposit (int amount) { // Do the deposit balance = balance + amount; System.out.println(balance); // Notify any threads that are waiting for a deposit to occur. notifyAll(); // Update the display. notifyListeners(); } /** * @return */ public synchronized int getBalance() { // TODO Auto-generated method stub return balance; } /** * @param bank */ public void addListener(AccountListener bank) { listeners.add(bank); } public void notifyListeners() { for (int i = 0; i < listeners.size(); i++) { listeners.get(i).balanceChanged(balance); } } }