Java Reference
In-Depth Information
In the last example, you could set priorities for the threads by modifying the
Clerk
and
TransactionSource
class constructors to accept an extra argument of type
int
. This would provide you with a program to play
with the effect of setting different thread priorities and you could experiment with different delays for doing
transactions in the bank. For example, you could change the
Clerk
class constructor to:
public Clerk(int ID, Bank theBank, int priority) {
this.ID = ID;
this.theBank = theBank; // Who the clerk works for
this.priority = priority;
}
You also need to add a new data member to the class to store the priority for the thread:
private int priority;
Of course, you
can
'
t
set the thread priority in the
constructor
. This is an easy mistake to make if you don't
think about what is going on. The constructor is executed in the main thread, not in the working clerk thread.
The place to set the priority for the clerk thread is at the beginning of the
run()
method. You need to add
the following as the first statement in the
run()
method:
Thread.currentThread().setPriority(priority); // Set priority for thread
This obtains a reference to the current thread by calling the static
currentThread()
method and then
uses that to call
setPriority()
for the thread.
The
TransactionSource
class constructor could be changed in a similar way:
public TransactionSource(TransactionType type, int maxTrans,
Vector<Account> accounts, Vector<Clerk> clerks, int priority) {
this.type = type;
this.maxTrans = maxTrans;
this.accounts = accounts;
this.clerks = clerks;
this.priority = priority;
totals = new int[accounts.size()];
}
You also need to add the
priority
member to the class. Setting the priority for the thread should be the
first statement in the
call()
method — it's the same statement as in the
run()
method in the
Clerk
class.
The
main()
method needs to be changed so the constructor calls pass a value for the priority of each
thread. Here's how you might set priorities for the clerk threads:
int priority = 0;
for(int i = 0 ; i < clerkCount ; ++i) {
priority = i%2 == 0 ? Thread.MIN_PRIORITY + (i + 1) : Thread.MAX_PRIORITY
- (i + 1);
if(priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY)
priority = Thread.NORM_PRIORITY;
clerks.add(new Clerk(i+1, theBank, priority)); // Create the clerks
}