參考網上查找的部分資料,對現有的代碼加入了自己的理解。
源碼來源:
http://sunnylocus.iteye.com/blog/223327
自己參考後的線程池:
package com.joker.log.util;
import java.util.LinkedList;
public class ThreadPool extends ThreadGroup {
private static int poolThreadId = 1;
private boolean isOpen;
private LinkedList<Runnable> workedQuences;
public ThreadPool(int poolSize) {
super(poolThreadId + "");
isOpen = true;
setDaemon(true);
workedQuences = new LinkedList<Runnable>();
for(int i=0;i<poolSize;i++){
new WorkThread(i).start();
}
}
public synchronized void excute(Runnable task){
if(!isOpen){
System.out.println("線程池已經關閉,不允許再加任務進入工作隊列");
throw new RuntimeException("線程池已經關閉");
}else{
workedQuences.add(task);
notify();
}
}
public void closeThreadpool(){
if(isOpen){
waitAllFinish();
workedQuences.clear();
isOpen =false;
////中斷線程池中的所有的工作線程,此方法繼承自ThreadGroup類
interrupt();
System.out.println("關閉線程池成功");
}
}
public void waitAllFinish(){
synchronized (this){
isOpen = false;
//喚醒全部等待的線程
notifyAll();
}
//activeCount(返回線程組中的估計活動數目)
Thread[]threads = new Thread[activeCount()];
//根據估計數,將線程組中活動的線程複製到指定的線程數組中
int count = enumerate(threads);
for(int i=0;i<count;i++){
try {
//等待所有的線程執行完畢
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class WorkThread extends Thread {
private int wordkThreadId;
public WorkThread(int id) {
// 將線程加入到當前線程組
super(ThreadPool.this, id + "");
this.wordkThreadId = id;
}
@Override
public void run() {
Runnable task;
while (!interrupted()) {
task = getTask(wordkThreadId);
if (null == task) {
System.out.println("線程池已經關閉,本次工作線程退出");
return;
} else {
try {
task.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
/**
*
* 待做任務爲空,等待
*
*/
private synchronized Runnable getTask(int id) {
while (workedQuences.size() == 0) {
if (!isOpen) {
return null;
}
System.out.println("任務隊列爲空線程" + id + "等待中");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("線程" + id + "開始執行任務。。。");
return workedQuences.removeFirst();
}
public Runnable createTask(final int i){
return new Runnable() {
@Override
public void run() {
System.out.println("第"+i+"個任務在執行中。。。。。");
}
};
}
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(10);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
pool.excute(pool.createTask(i));
}
pool.closeThreadpool();
}
}
1.5之後有現成的線程池,所以,這個線程池只是一個示例性代碼,理解原理用