//線程池
public class ThreadPool extends ThreadGroup {
private boolean isClosed = false; //線程池是否關閉
private LinkedList<Runnable> workQueue; //工作隊列
private static int threadPoolID = 1; //線程池的id
public ThreadPool(int poolSize) { //poolSize 表示線程池中的工作線程的數量
super(threadPoolID + ""); //指定ThreadGroup的名稱
setDaemon(true); //繼承到的方法,設定是否守護線程池
workQueue = new LinkedList<Runnable>(); //建立工作隊列
for(int i = 0; i < poolSize; i++) {
new WorkThread(i).start(); //建立并啟動工作線程,線程池數量是多少就建立多少個工作線程
}
}
public synchronized void execute(Runnable task) {
if(isClosed) {
throw new IllegalStateException();
}
if(task != null) {
workQueue.add(task);//向隊列中加入一個任務
notify(); //喚醒一個正在getTask()方法中待任務的工作線程
}
}
private synchronized Runnable getTask(int threadid) throws InterruptedException {
while(workQueue.size() == 0) {
if(isClosed) return null;
//System.out.println("工作線程"+threadid+"等待任務...");
wait(); //如果工作隊列中沒有任務,就等待任務
}
//System.out.println("工作線程"+threadid+"開始執行任務...");
return (Runnable) workQueue.removeFirst(); //反回隊列中第一個元素,并從隊列中删除
}
public synchronized void closePool() {
if(! isClosed) {
waitFinish(); //等待工作線程執行完畢
isClosed = true;
workQueue.clear(); //清空工作隊列
interrupt(); //中斷線程池中的所有的工作線程,此方法繼承自ThreadGroup類
}
}
public void waitFinish() {
synchronized (this) {
isClosed = true;
//喚醒所有還在getTask()方法中等待任務的工作線程
notifyAll();
}
//activeCount() 傳回該線程組中活動線程的估計值。
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) {
ex.printStackTrace();
}
}
}
private class WorkThread extends Thread {
private int id;
public WorkThread(int id) {
//父類構造方法,将線程加入到目前ThreadPool線程組中
super(ThreadPool.this,id+"");
this.id =id;
}
public void run() {
while(! isInterrupted()) { //isInterrupted()方法繼承自Thread類,判斷線程是否被中斷
Runnable task = null;
try {
task = getTask(id); //取出任務
}catch(InterruptedException ex) {
ex.printStackTrace();
}
//如果getTask()傳回null或者線程執行getTask()時被中斷,則結束此線程
if(task == null) return;
try {
task.run(); //運作任務
}catch(Throwable t) {
t.printStackTrace();
}
}// end while
}// end run
}// end workThread
}
//調用
ThreadPool threadPool = new ThreadPool(15);
for(int i = 0; i < 100; i++){
threadPool.execute(new Runnable(){
@Override
public void run(){
toDo();
}
});
}
threadPool.waitFinish();
threadPool.closePool();
轉載于:https://my.oschina.net/u/2619408/blog/878734