Java Reference
In-Depth Information
Try It Out - Setting Thread Priorities
We can extend the Clerk class to handle a number of Transaction objects by giving the in-tray the
capacity to store several transactions in a list, but not too many - we don't want to overwork the clerks.
The Collections class provides methods for creating synchronized sets, lists, and maps from
unsynchronized objects. The static synchronizedList() method in the Collections class accepts
an argument that is a list and returns a List object that is synchronized. We can use this to make our
inTray a synchronized list for storing transactions.
import java.util.List;
import java.util.Collections;
import java.util.LinkedList;
public class Clerk implements Runnable {
Bank theBank;
// The in-tray holding transactions
private List inTray = Collections.synchronizedList(new LinkedList());
private int maxTransactions = 8; // Maximum transactions in the in-tray
// Constructor
public Clerk(Bank theBank) {
this.theBank = theBank; // Who the clerk works for
//inTray = null; //Commented out: don't need this now
}
// Plus the rest of the class...
}
Note that we have deleted the statement from the constructor that originally set inTray to null . Now
that we are working with a list, we must change the doTransaction() method in the Clerk class to
store the transaction in the list as long as the tray is not full or, to say it another way, there are less than
maxTransactions in the list. Here's the revised code to do this:
synchronized public void doTransaction(Transaction transaction) {
while(inTray.size() >= maxTransactions) {
try {
wait();
} catch(InterruptedException e) {
System.out.println(e);
}
inTray.add(transaction);
notifyAll();
}
}
The size() method for the list returns the number of objects it contains so checking this is trivial. We
use the add() method to add a new Transaction object to the end of the list.
The run() method for a clerk retrieves objects from the in-tray so we must update that to deal with a list:
Search WWH ::




Custom Search