Java基础之线程——使用执行器(UsingExecutors)
控制台程序。
在这个版本的银行示例中,把借款和贷款事务创建为在不同线程中执行的任务,它们把事务提交给职员。创建事务的任务是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");
}
}
}
Java基础之线程——使用执行器(UsingExecutors)的更多相关文章
- Java基础-多线程-③线程同步之synchronized
使用线程同步解决多线程安全问题 上一篇 Java基础-多线程-②多线程的安全问题 中我们说到多线程可能引发的安全问题,原因在于多个线程共享了数据,且一个线程在操作(多为写操作)数据的过程中,另一个线程 ...
- 【Java基础】线程和并发机制
前言 在Java中,线程是一个很关键的名词,也是很高频使用的一种资源.那么它的概念是什么呢,是如何定义的,用法又有哪些呢?为何说Android里只有一个主线程呢,什么是工作线程呢.线程又存在并发,并发 ...
- Java基础篇——线程、并发编程知识点全面介绍(面试、学习的必备索引)
原创不易,如需转载,请注明出处https://www.cnblogs.com/baixianlong/p/10739579.html,希望大家多多支持!!! 一.线程基础 1.线程与进程 线程是指进程 ...
- Java基础_线程的使用及创建线程的三种方法
线程:线程是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务. 进程:进 ...
- Java基础之线程——管理线程同步方法(BankOperation2)
控制台程序. 当两个或多个线程共享同一资源时,例如文件或内存块,就需要采取措施,确保其中的一个线程不会修改另一个线程正在使用的资源.当其中的一个线程更新文件中的某个记录,同时另一个线程正在检索这个记录 ...
- Java基础之线程——使用Runnable接口(JumbleNames)
控制台程序. 除了定义Thread新的子类外,还可以在类中实现Runnable接口.您会发现这比从Thread类派生子类更方便,因为在实现Runnable接口时可以从不是Thread的类派生子类,并且 ...
- Java基础之线程——派生自Thread类的子类(TryThread)
控制台程序. 程序总是至少有一个线程,程序开始执行时就会创建这个线程.在普通的Java应用程序中,这个线程从mian()方法的开头启动. 要开始执行线程,可以调用Thread对象的start()方法. ...
- Java基础8-多线程;同步代码块
作业解析 利用白富美接口案例,土豪征婚使用匿名内部类对象实现. interface White{ public void white(); } interface Rich{ public void ...
- Java基础-多线程-①线程的创建和启动
简单阐释进程和线程 对于进程最直观的感受应该就是“windows任务管理器”中的进程管理: (计算机原理课上的记忆已经快要模糊了,简单理解一下):一个进程就是一个“执行中的程序”,是程序在计算机上的一 ...
随机推荐
- ecshop lang用法
ecshop lang用法 分类: ECSHOP2013-08-15 16:17 2184人阅读 评论(0) 收藏 举报 ecshop目录下的languages目录.这个是ecshop语言包所在.ec ...
- java--字符串替换replace,replaceAll,replaceFirst
1.字符串替换,replace string s="abcdfersabcdsgacabc"; 将字符串中的abc替换成bdf s.replace("abc", ...
- redis 应用场景
1.string类型 : 图片和视频文件,静态文件 2.list 双向链表:回帖ID,我的关注列表,消息队列 length = redis.lpush('users:newest', 'user:go ...
- Swapping
COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION Referring back to Fig ...
- P1091 合唱队形
水题 #include <bits/stdc++.h> using namespace std; const int maxn = 105; int main(int argc, char ...
- 最有用的Linux命令行使用技巧集锦
最近在Quora上看到一个问答题目,关于在高效率Linux用户节省时间Tips.将该题目的回答进行学习总结,加上自己的一些经验,记录如下,方便自己和大家参考. 下面介绍的都是一些命令行工具,这些工具在 ...
- iOS开发入门教程
iOS开发入门教程 http://my.oschina.net/mailzwj/blog/133273 摘要 iOS开发入门教程,从创建项目到运行项目,包括OC基础,调试,模拟器设置等相关知识. iO ...
- BLE-NRF51822教程-RSSI获取
当手机和设备连接上后,设备端可以通过获取RSSI,在一定程度上判断手机离设备的相对距离的远近. 获取函数很简单直接调用sd_ble_gap_rssi_get 接口函数就行了,传入连接句柄和buff就能 ...
- 转: PE rva to raw 虚拟偏移地址和文件物理偏移地址
+---------+---------+---------+---------+---------+---------+| 段名称 虚拟地址 虚拟大小 物理地址 物理大小 标志 |+-------- ...
- 转:[ASP.NET]重構之路系列v4 – 簡單使用interface之『你也會IoC』
前言 上次v3版本,我們將Entity, Service, Dao, Utility都放到了類別庫裡面,讓我們可以輕鬆的在不同專案中用同一份組件.雖然文章沒有獲得太多的讚賞,不過相信那一定是太多人會這 ...