標籤:io ar os sp for java on art bs
package Chapter3;
import java.util.LinkedList;
public class ThreadPool extends ThreadGroup {
private boolean isClosed = false; // 線程池是否關閉
private LinkedList<Runnable> workQueue; // 表示工作隊列,用來存放線程池要執行的任務,每個任務都是Runnable執行個體
private static int threadPoolID; // 表示線程池ID
private int threadID; // 表示背景工作執行緒ID
public ThreadPool(int poolSize) { // poolSize指定線程池中的背景工作執行緒數目
super("TheadPool-" + (threadPoolID++));
setDaemon(true);
workQueue = new LinkedList<Runnable>(); // 建立工作隊列
for (int i = 0; i < poolSize; i++)
new WorkThread().start(); // 建立並啟動背景工作執行緒
}
/** 向工作隊列中加入一個新的任務,由背景工作執行緒去執行該任務 */
public synchronized void execute(Runnable task) {
if (isClosed) {// 線程池被關閉則拋出IllegalStateException異常
throw new IllegalStateException();
}
if (task != null) {
workQueue.add(task);
notify();// 喚醒正在getTask()方法中等待的背景工作執行緒
}
}
/** 從工作隊列中取出一個任務,背景工作執行緒會調用此方法 */
protected synchronized Runnable getTask() throws InterruptedException {
while (workQueue.size() == 0) {
if (isClosed)
return null;
wait();// 如果工作隊列中沒有任務,就等待任務
}
return workQueue.removeFirst();
}
/** 關閉線程池 */
public synchronized void close() {
if (!isClosed) {
isClosed = true;
workQueue.clear();// 清空工作隊列
interrupt();// 中斷所有的背景工作執行緒,該方法繼承自ThreadGroup類
}
}
/** 等待背景工作執行緒把所有任務執行完 */
public void join() {
synchronized (this) {
isClosed = true;
notifyAll();// 喚醒還在getTask()方法中等待任務的動作線程
}
Thread[] threads = new Thread[activeCount()];
// enumerate()方法繼承自ThreadGroup類,獲得線程組中當前所有活著的背景工作執行緒
int count = enumerate(threads);
for (int i = 0; i < count; i++) {// 等待所有背景工作執行緒運行結束
try {
threads[i].join();// 等待背景工作執行緒運行結束
} catch (InterruptedException ex) {
}
}
}
/** 內部類:背景工作執行緒 */
private class WorkThread extends Thread {
public WorkThread() {
// 加入當前ThreadPool線程組中
super(ThreadPool.this, "WorkThread-" + (threadID++));
}
public void run() {
while (!isInterrupted()) {// isInterrupted()方法繼承自Thread類,判斷線程是否被中斷
Runnable task = null;
try {// 取出任務
task = getTask();
} catch (InterruptedException ex) {
}
/**
* 如果getTask()返回null或線程執行getTask()時被中斷,則結束此線程
*/
if (task == null)
return;
try {// 運行任務,異常在catch代碼塊中捕獲
task.run();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
}
socket編程3-ThreadPool