线程池的实现

参考网上查找的部分资料,对现有的代码加入了自己的理解。

源码来源:

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之后有现成的线程池,所以,这个线程池只是一个示例性代码,理解原理用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章