Java Reference
In-Depth Information
// Constructor
public Clerk(Bank theBank) {
this.theBank = theBank; // Who the clerk works for
inTray = null; // No transaction initially
}
// Receive a transaction
public void doTransaction(Transaction transaction) {
inTray = transaction;
}
// The working clerk...
public void run() {
while(true) {
while(inTray == null) { // No transaction waiting?
try {
Thread.sleep(150); // Then take a break...
} catch(InterruptedException e) {
System.out.println(e);
}
}
theBank.doTransaction(inTray);
inTray = null; // In-tray is empty
}
}
// Busy check
public boolean isBusy() {
return inTray != null; // A full in-tray means busy!
}
}
How It Works
A Clerk object is a thread since it implements the Runnable interface. Each clerk has an in-tray,
capable of holding one transaction, and while the in-tray is not null , the clerk is clearly busy. A clerk
needs to be aware of the Bank object that is employing him or her, so a reference is stored in theBank
when a Clerk object is created. A transaction is placed in the in-tray for a clerk by calling his or her
doTransaction() method. You can check whether a clerk is busy by calling the isBusy() member
which will return true if a transaction is still in progress.
The real work is actually done in the run() method. If the in-tray is empty, indicated by a null value
in inTray , then there's nothing to do, so after sleeping a while the loop goes around again for another
look at the in-tray. When a transaction has been recorded, the method in theBank object is called to
carry it out and the inTray is reset to null .
All we need now is the class to drive our model world, which we will call BankOperation . This class
only requires the method main() , but there are quite a lot of things to do in this method so we'll put it
together piece by piece.
Search WWH ::




Custom Search