Java Reference
In-Depth Information
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. We will 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
}
}
The import for the Random class is there because we will need it in a moment. To create the Bank
object, the clerks, and the account, we 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 a lot, but is quite repetitive:
// Generate transactions of each type and pass to the clerks
Random rand = new Random(); // Random number generator
Search WWH ::




Custom Search