Java Reference
In-Depth Information
synchronized public void run() {
while(true) {
while(inTray.size() == 0) { // No transaction waiting?
try {
wait(); // Then take a break until there is
} catch(InterruptedException e) {
System.out.println(e);
}
theBank.doTransaction((Transaction)inTray.remove(0));
notifyAll(); // Notify other threads locked on this clerk
}
}
The remove() method in the List interface that we are using here removes the object at the index
position in the list specified by the argument and returns a reference to it. Since we use 0 as the index
we retrieve the first object in the list to pass to the doTransaction() method for the Bank object.
Since we now use a list to store transactions, the isBusy() method for a Clerk object also needs
to be changed:
synchronized public void isBusy() {
while(inTray.size() != 0) { // Is this object busy?
try {
wait(); // Yes, so wait for notify call
} catch(InterruptedException e) {
System.out.println(e);
}
}
return; // It is free now
}
Now the clerk is not busy if there are no transactions in the inTray list. Hence we test the value
returned by size() .
That's all we need to buffer transactions in the in-tray of each clerk. If you reactivate the output
statements that we added to the method in the Bank class, you'll be able to see how the processing of
transactions proceeds.
With the priorities set by the calls to setPriority() we saw earlier, the processing of credits should
run ahead of the processing of debits, although the fact that the time to process a debit is longer than the
time for a credit will also have a significant effect. To make the thread priority the determining factor,
set the times in the calls to the sleep() method in the Bank class to the same value. You could then
try changing the values for priorities around to see what happens to the sequence in which transactions
are processed. Of course, if your operating system does not support priority scheduling, then it won't
have any effect anyway.
Search WWH ::




Custom Search