Java Reference
In-Depth Information
Directory "BankOperation 1"
How It Works
A Clerk object is a thread because it implements the Runnable interface. Each clerk has an in-tray, cap-
able of holding one transaction, and although 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 returns 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 for the clerk to do, so after sleeping a while, the loop goes around again to
give the clerk another look at the in-tray. When a transaction has been recorded in the in-tray, the method
in theBank object is called to carry it out, and the inTray is reset to null .
All you need now is the class to drive our model world, which you can call BankOperation . This class
requires only the method main() , but there are quite a lot of things to do in this method so you put it
together piece by piece.
TRY IT OUT: Defining the Operation of the Bank
Apart from setting everything up, the main() method has to originate transactions on the accounts and
pass them on to the clerks to be expedited. You start with just one account and a couple of clerks. Here's
the basic structure:
import java.util.Random;
public class BankOperation {
public static void main(String[] args) {
int initialBalance = 500;
// The initial account balance
int totalCredits = 0;
// Total credits on the account
int totalDebits =0;
// Total debits on the account
int transactionCount = 20;
// Number of debits and credits
// Create the account, the bank, and the clerks...
// Create the threads for the clerks as daemon, and start them off
// Generate the transactions of each type and pass to the clerks
// Wait until both clerks are done
// Now output the results
}
Search WWH ::




Custom Search