Java Reference
In-Depth Information
The class implements
Callable<int[]>
because a task returns an array of values of type
int
. The con-
structor expects four arguments: the type of transactions to be generated,
DEBIT
or
CREDIT
, the maximum
number of transactions to be created, a reference to a
Vector<Account>
containing the accounts, and a
reference to a
Vector<Clerk>
containing the clerks. The constructor just stores these in the object and
creates an array of the appropriate size to store the total value of the transactions created for each ac-
count.
The
call()
method returns a reference of type
int[]
, which is a reference to the array of totals. The
for
loop generates the transactions in much the same way as the previous example. Having created a transac-
tion, the method tries to assign the transaction to a clerk in an indefinite
while
loop. It searches through
the
clerks
vector to find a clerk that can accept a transaction; you implement the
doTransaction()
method for a
Clerk
object to return
true
if the transaction can be accepted and
false
otherwise. If a
clerk accepts the transaction, the indefinite
while
loop is terminated and the outer
for
loop continues.
If no clerk is free, the method calls
sleep()
to wait a while before trying again to see if a clerk has be-
come free. This continues until a clerk does become free or until the thread is interrupted.
On each iteration of the outer for loop that generates transactions, you call the static
interrupted()
method for the
Thread
class to allow the possibility for the thread to be canceled externally. If you don't
do this, the only possibility for canceling the thread is while it is sleeping. When the
call()
method
ends, it returns a reference to the
totals
array.
Defining a Clerk
Each clerk also runs as a separate thread, but because a clerk does not need to return a value, you can
define it as a
Runnable
class:
import java.util.List;
import java.util.Collections;
import java.util.LinkedList;
public class Clerk implements Runnable {
// Constructor
public Clerk(int ID, Bank theBank) {
this.ID = ID;
this.theBank = theBank;
// Who the clerk works for
}
// Receive a transaction
synchronized public boolean doTransaction(Transaction transaction) {
if(inTray.size() >= maxTransactions)
return false;
inTray.add(transaction);
// Add transaction to the list
return true;
}
// The working clerk...
public void run() {
while(true) {
while(inTray.size() == 0) {
// No transaction waiting?