Java Reference
In-Depth Information
This assigns priorities alternating between high and low priorities to get a large divergence between the
threads. If the number of clerks was set greater than MAX_PRIORITY 1 , you could end up with invalid pri-
ority values so the if statement verifies that everything is legal and sets NORM_PRIORITY in place of invalid
values.
You could amend the calls to the TransactionSource constructor to the following:
Future<int[]> credits = threadPool.submit(
new TransactionSource(
TransactionType.CREDIT, transactionCount,
accounts, clerks, Thread.MAX_PRIORITY-1));
Future<int[]> debits = threadPool.submit(
new TransactionSource(
TransactionType.DEBIT, transactionCount,
accounts, clerks, Thread.MIN_PRIORITY+1));
I won't go through this in detail as the example really is just for experimenting with threads. The complete
example is in the download in the SettingThreadPriorities directory. This includes some changes to
track which clerk is doing each transaction. Whether or not thread priorities have any effect depends on your
operating system. If it doesn't support thread priorities, then setting thread priorities in your Java code has
no effect. Try out the program to see what happens.
SUMMARY
In this chapter you learned about threads and the basics of how you can create and manage them. You use
threads from time to time in examples later in this topic, so be sure you don't move on from here without
being comfortable with the basic ideas of how you create and start a thread.
In general, thread programming is not for the faint-hearted. Thread programming is difficult, even for
experienced programmers. It is hard for most people to visualize clearly what is happening when multiple
threads are executing and it is easy to get things wrong, sometimes in very subtle ways. It is therefore
something to venture into only when there are clear performance benefits to be gained.
EXERCISES
You can download the source code for the examples in the topic and the solutions to the following exer-
cises from www.wrox.com .
1. Modify the UsingExecutors example in the chapter so that each transaction is a debit or a credit at
random.
2. Modify the result of the previous exercise to allow an arbitrary number of transaction source objects
to be in effect.
3. Extend the result of the previous exercise to incorporate two supervisors for two teams of clerks,
where the supervisors each run in their own thread. The supervisor threads should receive transactions
from transaction sources and pass them to the clerks they supervise. The supervisors' work should
result in a variable time delay in transferring transaction to the clerks of between 100 and 500 milli-
seconds.
Search WWH ::




Custom Search