Java Reference
In-Depth Information
private Transaction inTray; // The in-tray holding a transaction
// Constructor
public Clerk(Bank theBank) {
this.theBank = theBank; // Who the clerk works for
inTray = null; // No transaction initially
}
// Receive a transaction
synchronized public void doTransaction(Transaction transaction) {
while(inTray != null) {
try {
wait();
} catch(InterruptedException e) {
System.out.println(e);
}
}
inTray = transaction;
notifyAll();
}
// Rest of the class as before...
}
When
inTray
is
null
, the transaction is stored and the
notifyAll()
method is called to notify
other threads waiting on a change to this
Clerk
object. If
inTray
is not
null
, this method waits until
some other thread calls
notifyAll()
to signal a change to the
Clerk
object. We now need to
consider where the
inTray
field is going to be modified elsewhere. The answer is in the
run()
method for the
Clerk
class, of course, so we need to change that too:
synchronized public void run() {
while(true) {
while(inTray == null) // No transaction waiting?
try {
wait(); // Then take a break until there is
} catch(InterruptedException e) {
System.out.println(e);
}
theBank.doTransaction(inTray);
inTray = null; // In-tray is empty
notifyAll(); // Notify other threads locked on this clerk
}
}
// Rest of the class as before...
}
Just to make it clear which methods are in what threads, the situation in our program is illustrated below.