Threads and Synchronization - Example
Suppose that several threads are updating a bank balance (i.e., several threads can access one instance of class Account below). Then a thread that finds insufficient funds to debit an account can wait until another thread adds to the account:
- public class Account
- { int bankBalance; ...
- public synchronized void DebitAcct (int amt)
- { while ((bankBalance - amt) < 0) wait();
- bankBalance -= amt; ... }
- public synchronized void CreditAcct (int amt)
- { bankBalance += amt;
- notify(); ... } }