import java.util.ArrayList; public class Account { // The current balance in the account. private int balance = 1000; // Protected by lock on "this" private ArrayList listeners = new ArrayList(); /** * Withdraw money from the account. This method is synchronized so that only one * thread at a time can access the account balance. * @param amount the amount to withdraw. */ public synchronized void withdraw (int amount) { //balance = balance - amount; int newBalance = balance - amount; Thread.yield(); balance = newBalance; notifyListeners(); } /** * Deposit money into the account. This method is synchronized so that only one * thread at a time can access the account balance. * @param amount the amount to deposit. */ public synchronized void deposit (int amount) { //balance = balance + amount; int newBalance = balance + amount; Thread.yield(); balance = newBalance; notifyListeners(); } /** * Returns the account balance. This method is synchronized to guarantee that * the balance is read from memory, not from a cache on a multiprocessor. * @return the account balance */ 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); } } }