一個(gè)線程池由線程池管理器 工作線程 任務(wù)隊(duì)列和任務(wù)接口組成
一 線程池管理器---ThreadPoolMananger 主要負(fù)責(zé)啟動(dòng) 停止工作線程
- public class ThreadPoolManager {
- private static int DEFAULT_POOL_SIZE = 4;
- private List<WorkThread> threadPool;
- private Queue<Task> taskQueue;
- private int poolSize;
- public ThreadPoolManager(){
- this(DEFAULT_POOL_SIZE);
- }
- public ThreadPoolManager(int poolSize){
- if(poolSize <= 0){
- this.poolSize = DEFAULT_POOL_SIZE;
- }else{
- this.poolSize = poolSize;
- }
- threadPool = new ArrayList<WorkThread>(this.poolSize);
- taskQueue = new ConcurrentLinkedQueue<Task>();
- startup();
- }
- /**
- * 啟動(dòng)線程池 開(kāi)始處理任務(wù)
- */
- private void startup(){
- System.out.println("啟動(dòng)工作線程。。。");
- synchronized(taskQueue){
- for(int i = 0; i < DEFAULT_POOL_SIZE; i++){
- WorkThread workThread = new WorkThread(taskQueue);
- threadPool.add( workThread );
- workThread.start();
- }
- }
- }
- /**
- * 停止工作線程。工作線程不一定立即停止,只有在線程處于運(yùn)行狀態(tài)時(shí)會(huì)立即停止
- */
- public void shutdown(){
- System.out.println("停止工作線程.");
- synchronized(taskQueue){
- for(int i = 0; i < DEFAULT_POOL_SIZE; i++){
- threadPool.get(i).shutdown();
- }
- }
- }
- /**
- * 添加消息到隊(duì)尾,
- */
- public void addTask(Task task){
- synchronized(taskQueue){
- taskQueue.add(task);
- taskQueue.notifyAll();
- }
- }
- }
二 工作線程---WorkerThread 顧名思義 它本身就是一個(gè)線程,而且是專門用來(lái)工作的,工作線程的主要任務(wù)是從任務(wù)隊(duì)列中取出任務(wù) 然后執(zhí)行任務(wù)
三 任務(wù)隊(duì)列---TaskQueue FIFO數(shù)據(jù)結(jié)構(gòu) 在出對(duì)入隊(duì)的時(shí)候要鎖定對(duì)象避免兩個(gè)線程重復(fù)處理某任務(wù)
在這里我采用的是java提供的ConcurrentLinkedQueue隊(duì)列,這是一個(gè)用鏈表實(shí)現(xiàn)的隊(duì) 可無(wú)限的擴(kuò)大,具體用法請(qǐng)看doc
用到隊(duì)列的地方主要有兩個(gè) addTask(Task task) 和 Task task = queue.poll();
四 任務(wù)接口---Task 任務(wù)接口只有一個(gè)方法 execute(),使用者只需實(shí)現(xiàn)這個(gè)接口就可以了
用法:
可以看出用戶的使用非常簡(jiǎn)單
在jdk5中 java提供了線程池
有一點(diǎn)注意 千萬(wàn)不要在servlet中調(diào)用線程池 因?yàn)閟ervlet本來(lái)就是一個(gè)線程池