Java Reference
In-Depth Information
You can test whether all tasks in a thread pool have been shut down by calling the
isTerminated()
meth-
od for the
ExecutorService
object. This method returns
true
if either
shutdown()
or
shutdownNow()
has
been called and all tasks have ended. The
isShutdown()
method returns
true
if the executor has been shut
down.
Let's try an executor in an example.
TRY IT OUT: Using an Executor
This example implements a version of the bank using an executor to execute the treads. The
Account
and
Transaction
classes and the
TransactionType
enum are the same as for the previous example. I
call the class that defines the
main()
method
UsingExecutors
.
In this version of the bank, you create debit and credit transactions as tasks executing in separate threads
that submit transactions to the clerks. The tasks that create transactions are
Callable<>
tasks because
they need to return the total value of the debit or credit transactions that have been created for each ac-
count.
Generating Transactions
Here's a definition of the class identifying a source of transactions:
// Generates transactions for clerks
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.Callable;
public class TransactionSource implements Callable<int[]> {
// Constructor
public TransactionSource(TransactionType type, int maxTrans,
Vector<Account> accounts,
Vector<Clerk> clerks) {
this.type = type;
this.maxTrans = maxTrans;
this.accounts = accounts;
this.clerks = clerks;
totals = new int[accounts.size()];
}
// The source of transactions
public int[] call() {
// Create transactions randomly distributed between the accounts
Random rand = new Random();
Transaction transaction = null;
// Stores a
transaction
int amount = 0;
// Stores
an amount of money
int select = 0;
// Selects