Java Reference
In-Depth Information
All clerks have completed their tasks.
Account Number:1
Original balance : $500
Total credits : $570
Total debits : $704
Final balance : $366
Should be : $366
Account Number:2
Original balance : $800
Total credits : $683
Total debits : $496
Final balance : $987
Should be : $987
When you run the example, you will almost certainly see different output.
How It Works
The initialization in main() that occurs before the ExecutorService object is created is much the same
as the previous example. The principle difference is that the clerks and accounts are now stored in Vect-
or<> collection objects. You have the possibility of specifying an arbitrary number of accounts by in-
creasing the number of values in the initialBalance array and increasing the number of clerks by
changing the value specified for clerkCount . If you want more transactions, just change the value of
transactionCount . I kept the number low for everything to keep the volume of output at modest levels.
After the accounts and clerks have been created, you obtain an ExecutorService reference to an execut-
or object by calling the newCachedThreadPool() factory method from the Executors class:
ExecutorService threadPool = Executors.newCachedThreadPool();
This provides as many threads as you require.
You create the TransactionSource objects in the arguments to the submit() method for the Execut-
orService object:
Future<int[]> credits = threadPool.submit(new TransactionSource(
TransactionType.CREDIT, transactionCount, accounts,
clerks));
Future<int[]> debits = threadPool.submit(new TransactionSource(
TransactionType.DEBIT, transactionCount, accounts,
clerks));
You only need references to the Future<> objects that are returned by the submit() method because
these give you access to the value returned by the Callable<> threads as well as the means of controlling
their execution. The type parameter for the Future<> type specification corresponds to the type of value
that each thread returns. After executing these statement, you have two new threads running.
You create and start the Clerk threads in a loop:
for(Clerk clerk : clerks) (
threadPool.submit(clerk);
Search WWH ::




Custom Search