Java Reference
In-Depth Information
}
Directory "BankOperation 1"
The import for the Random class is there because you need it for code you add a little later. To create the
Bank object, the clerks, and the account, you need to add the following code:
// Create the account, the bank, and the clerks...
Bank theBank = new Bank(); // Create a bank
Clerk clerk1 = new Clerk(theBank); // Create the
first clerk
Clerk clerk2 = new Clerk(theBank); // Create the
second clerk
Account account = new Account(1, initialBalance);// Create an
account
The next step is to add the code to create the threads for the clerks and start them going:
// Create the threads for the clerks as daemon, and start them off
Thread clerk1Thread = new Thread(clerk1);
Thread clerk2Thread = new Thread(clerk2);
clerk1Thread.setDaemon(true); // Set first
as daemon
clerk2Thread.setDaemon(true); // Set second
as daemon
clerk1Thread.start(); // Start the
first
clerk2Thread.start(); // Start the
second
The code to generate the transactions looks like a lot but is quite repetitive:
// Generate transactions of each type and pass to the clerks
Random rand = new Random(); // Random
number generator
Transaction transaction; // Stores a
transaction
int amount = 0; // stores an
amount of money
for(int i = 1 ; i <= transactionCount ; ++i) {
amount = 50 + rand.nextInt(26); // Generate
amount of $50 to $75
transaction = new Transaction(account, // Account
TransactionType.CREDIT, // Credit
transaction
amount); // of amount
totalCredits += amount; // Keep total
credit tally
// Wait until the first clerk is free
while(clerk1.isBusy()) {
try {
Search WWH ::




Custom Search