Develop a Java class to solve this problem (i.e. translate the monitor solution to exercise 4 into Java). In addition to the constructor, the class should have two public methods: deposit(int amount) and withdraw(int amount). Assume the arguments to deposit and withdraw are postive.
class SavingsAccount {
protected long balance;
public SavingsAccount(long openingBalance) {
balance = openingBalance;
}
public synchronized void deposit(int amount) {
balance += amount;
notifyAll();
}
public synchronized withdraw(int amount) throws InterruptedException {
while (amount > balance)
wait();
balance -= amount;
}
}
The solution is very similar to that using monitors. The current balance is
held in the private integer field, balance. Mutual exclusion is explicit and indicated by the
synchronized keyworld; condition
synchronisation is achieved using wait
and notifyAll, the latter being used to
indicate that funds have been deposited.
This file is maintained by Brian Logan Last modified: 17:37, 13-Mar-2007