Java Reference
In-Depth Information
clerk2Thread
clerk1Thread
main thread
clerk1
clerk2
main()
synchronized on
synchronized on
clerk2.run()
clerk1.doTransaction()
clerk1.run()
theBank.doTransaction()
theBank.doTransaction()
clerk2.doTransaction()
Credit operation:
Credit operation:
Debit operation:
Debit operation:
synchronized on
snchro
y
nized on
an
account
an
account
Here the run() method is synchronized on the Clerk object that contains it, and the method waits if
inTray is null . Eventually the doTransaction() method for the current object should store a
transaction in inTray , and then notify the thread that is waiting that it should continue.
It may seem odd having two methods in the same object synchronized on one and the same object that
owns them, but remember that the run() and doTransaction() methods for a particular Clerk
object are in separate threads.
The transaction processing method for the bank can be in both of the clerk threads, whereas the
methods that hand over a transaction to a clerk are in the main thread. The diagram also shows which
code is synchronized on what objects.
We can now modify the code in the for loop in main() to pass the transactions directly to the clerks.
Except for deleting the two while loops that wait until the clerks are free, the code is exactly as before:
// Create transactions randomly distributed between the accounts
for(int i = 1; i <= transactionCount; i++) {
// Generate a random account index for credit operation
select = rand.nextInt(accounts.length);
amount = 50 + rand.nextInt(26); // Generate amount of $50 to $75
transaction = new Transaction(accounts[select], // Account
Transaction.CREDIT, // Credit transaction
amount); // of amount
totalCredits[select] += amount; // Keep total credit tally
clerk1.doTransaction(transaction); // Now do the credit
// Generate a random account index for debit operation
select = rand.nextInt(accounts.length);
Search WWH ::




Custom Search