控制台程序。

在这个版本的银行示例中,把借款和贷款事务创建为在不同线程中执行的任务,它们把事务提交给职员。创建事务的任务是Callable<>任务,因为它们需要返回已为每个账户创建的借款或贷款事务的总额。

 // Defines a customer account
public class Account {
// Constructor
public Account(int accountNumber, int balance) {
this.accountNumber = accountNumber; // Set the account number
this.balance = balance; // Set the initial balance
} // Return the current balance
public int getBalance() {
return balance;
} // Set the current balance
public void setBalance(int balance) {
this.balance = balance;
} public int getAccountNumber() {
return accountNumber;
} @Override
public String toString() {
return "A/C No. " + accountNumber + " : $" + balance;
} private int balance; // The current account balance
private int accountNumber; // Identifies this account
}
 // Bank account transaction types
public enum TransactionType {DEBIT, CREDIT }
 public class Transaction {
// Constructor
public Transaction(Account account, TransactionType type, int amount) {
this.account = account;
this.type = type;
this.amount = amount;
} public Account getAccount() {
return account;
} public TransactionType getTransactionType() {
return type;
} public int getAmount() {
return amount;
}
@Override
public String toString() {
return type + " A//C: " + ": $" + amount;
} private Account account;
private int amount;
private TransactionType type;
}
 // Define the bank

 public class Bank {
// Perform a transaction
public void doTransaction(Transaction transaction) {
synchronized(transaction.getAccount()) {
int balance = 0;
switch(transaction.getTransactionType()) {
case CREDIT:
System.out.println("Start credit of " +
transaction.getAccount() + " amount: " +
transaction.getAmount()); // Get current balance
balance = transaction.getAccount().getBalance(); // Credits require a lot of checks...
try {
Thread.sleep(100); } catch(InterruptedException e) {
System.out.println(e);
}
balance += transaction.getAmount(); // Increment the balance
transaction.getAccount().setBalance(balance); // Restore account balance
System.out.println(" End credit of " +
transaction.getAccount() + " amount: " +
transaction.getAmount());
break;
case DEBIT:
System.out.println("Start debit of " +
transaction.getAccount() + " amount: " +
transaction.getAmount()); // Get current balance
balance = transaction.getAccount().getBalance(); // Debits require even more checks...
try {
Thread.sleep(150); } catch(InterruptedException e) {
System.out.println(e);
}
balance -= transaction.getAmount(); // Decrement the balance...
transaction.getAccount().setBalance(balance); // Restore account balance 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);
}
}
}
}
 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?
try {
Thread.sleep(200); // then take a break
if(inTray.size() != 0) {
break;
} else {
return;
}
} catch(InterruptedException e) {
System.out.println("Clerk "+ ID + "\n" + e);
return;
}
}
theBank.doTransaction(inTray.remove(0));
if(Thread.interrupted()) {
System.out.println("Interrupt flag for Clerk " + ID + " set. Terminating.");
return;
}
}
} int ID;
private Bank theBank;
private List<Transaction> inTray = // The in-tray holding transactions
Collections.synchronizedList(new LinkedList<Transaction>());
private int maxTransactions = 8; // Maximum transactions in the in-tray
}
 // Generates transactions for clerks
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.Callable; public class TransactionSource implements Callable<int[]> { 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 an account
boolean done = false;
for(int i = 1 ; i <= maxTrans ; ++i) {
// Generate a random account index for operation
select = rand.nextInt(accounts.size());
amount = 50 + rand.nextInt(26); // Generate amount of $50 to $75
transaction = new Transaction(accounts.get(select), // Account
type, // Transaction type
amount); // of amount
totals[select] += amount; // Keep total tally for account
done = false;
while(true) {
// Find a clerk to do the transaction
for(Clerk clerk : clerks) {
if(done = clerk.doTransaction(transaction))
break;
}
if(done) {
break;
} // No clerk was free so wait a while
try {
Thread.sleep(10);
} catch(InterruptedException e) {
System.out.println(" TransactionSource\n" + e);
return totals;
}
}
if(Thread.interrupted()) {
System.out.println("Interrupt flag for "+ type + " transaction source set. Terminating.");
return totals;
}
}
return totals;
} private TransactionType type;
private int maxTrans;
private Vector<Account> accounts;
private Vector<Clerk> clerks;
private int[] totals;
}
 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 different cr totals
int[] totalDebits = new int[initialBalance.length]; // Two different db totals
int transactionCount = 20; // Number of debits and of credits
int clerkCount = 2; // Create the account, the bank, and the clerks...
Bank theBank = new Bank(); // Create a bank
Vector<Clerk> clerks = new Vector<Clerk>(); // Stores the clerk
Vector<Account> accounts = new Vector<Account>(); // Stores the accounts for(int i = 0 ; i < clerkCount ; ++i) {
clerks.add(new Clerk(i+1, theBank)); // Create the clerks
} for(int i = 0 ; i < initialBalance.length; ++i) {
accounts.add(new Account(i+1, initialBalance[i])); // Create accounts
totalCredits[i] = totalDebits[i] = 0;
} ExecutorService threadPool = Executors.newCachedThreadPool(); // Create and start the transaction source threads
Future<int[]> credits = threadPool.submit(new TransactionSource(TransactionType.CREDIT, transactionCount, accounts, clerks));
Future<int[]> debits = threadPool.submit(new TransactionSource(TransactionType.DEBIT, transactionCount, accounts, clerks)); // Create and start the clerk threads
for(Clerk clerk : clerks) {
threadPool.submit(clerk);
}
try {
totalCredits = credits.get();
totalDebits = debits.get();
} catch(ExecutionException e) {
System.out.println(e.getCause());
} catch(InterruptedException e) {
System.out.println(e);
} // Orderly shutdown when all threads have ended
threadPool.shutdown();
try {
threadPool.awaitTermination(10L, TimeUnit.SECONDS);
} catch(InterruptedException e) {
System.out.println(e);
} if(threadPool.isTerminated()) {
System.out.println("\nAll clerks have completed their tasks.\n");
} else {
System.out.println("\nClerks still running - shutting down anyway.\n");
threadPool.shutdownNow();
} // Now output the results
for(int i = 0 ; i < accounts.size() ; ++i) {
System.out.println("Account Number:"+accounts.get(i).getAccountNumber()+"\n"+
"Original balance : $" + initialBalance[i] + "\n" +
"Total credits : $" + totalCredits[i] + "\n" +
"Total debits : $" + totalDebits[i] + "\n" +
"Final balance : $" + accounts.get(i).getBalance() + "\n" +
"Should be : $" + (initialBalance[i]
+ totalCredits[i]
- totalDebits[i]) + "\n");
}
}
}

最新文章

  1. android 查看MD5、sha1值命令
  2. C#中几种换行符
  3. 修改XPMenu让ToolButton在Down=True时正确显示
  4. SPL學習之SplDoublyLinkedList
  5. Spring4整合quartz2.2.3,quartz动态任务
  6. HDU3336 Count the string
  7. selenium 执行js,实现滚动条
  8. CH4INRULZ从渗透到提权
  9. Kubernetes基本功能
  10. openstack之neutron配额调整
  11. java流程控制语句总结
  12. awk 进阶,百万行文件取交集
  13. vim中行末去掉^M
  14. git review filter的一些规则
  15. Python3基础 list insert 在指定位置挤入一个元素
  16. sql -- 移除数据中的换行符和回车符
  17. 【mybatis源码学习】mybatis和spring框架整合,我们依赖的mapper的接口真相
  18. sql 题目
  19. .Net Core使用OpenXML导出,导入Excel
  20. codevs——2181 田忌赛马

热门文章

  1. java 时间戳和PHP时间戳 的转换
  2. WordPress博客教程:博客赚钱
  3. PHP关闭提示、打印配置
  4. Levenshtein distance
  5. DML以及DQL的使用方法
  6. Java Blocking Queue
  7. Python中定义字符串
  8. 实验三--for语句及分支结构else-if
  9. NRF51822之app_button使用
  10. vim编辑器配置修改