Java Reference
In-Depth Information
System.out.println(" End debit of " +
transaction.getAccount() + " amount: " +
transaction.getAmount());
break;
default:
// We should
never get here
System.out.println("Invalid transaction");
System.exit(1);
}
}
}
}
Directory "UsingExecutors"
The doTransaction() method for the Bank object is executed in a Clerk thread. The code in the
doTransaction() method for the bank is synchronized on the account to which the transaction applies.
This ensures that only one clerk can access any given account at a time. As before, debits take longer
than credits to process. The doTransaction() method includes output for each transaction that is pro-
cessed so you can see all the details of what goes on in the bank before that final accounts are displayed.
Running Banking Operations
The main() method creates and initiates all the threads that operate the bank. Here's the class definition:
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class UsingExecutors {
public static void main(String[] args) {
int[] initialBalance = {500, 800};
// The initial
account balances
int[] totalCredits = new int[initialBalance.length]; // Two cr
totals
int[] totalDebits = new int[initialBalance.length]; // Two db
totals
int transactionCount = 20;
// Number of debits and
of credits
int clerkCount = 2;
// Create the account, the bank, and the clerks...
Search WWH ::




Custom Search