Basic HTML version of Foils prepared
Sept 21 1998
Foil 14 Threads and Synchronization - Example
From
Java Tutorial 98- 4: Multi-Treading, Useful Java Classes, I/O and Networking NAVO Tutorial --
Sept 23 1998
.
by
Geoffrey C. Fox, Nancy McCracken
1
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(); ... } }
in Table To:
©
Northeast Parallel Architectures Center, Syracuse University, npac@npac.syr.edu
If you have any comments about this server, send e-mail to
webmaster@npac.syr.edu
.
Page produced by
wwwfoil
on Sat Nov 28 1998