import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeSet;

public class ThreadPool extends ThreadGroup {

 private LinkedList<Runnable> workQueue = null; // 工作队列

 private static int coreActiveSize = 1;//核心线程个数

 private static int maxActiveSize = 5;//允许最大线程个数

 private static ThreadPool threadPool;//单例

 Set<Integer> threadIdSet = new TreeSet<Integer>();//有序线程队列

 /**

  * private constructor
  *
  * @param poolSize
  */
 private ThreadPool() { // poolSize
  // 表示线程池中的工作线程的数量
  super("AllReportPool"); // 指定ThreadGroup的名称
  if (coreActiveSize <= 0 || maxActiveSize <= 0) {
   throw new IllegalArgumentException(
     "Thread Pool active size should be much more than 0");
  }
  if (coreActiveSize > maxActiveSize) {
   throw new IllegalArgumentException(
     "Thread Pool max active size should be much more than core active size");
  }
  setDaemon(false); // 继承到的方法,设置是否守护线程池
  workQueue = new LinkedList<Runnable>(); // 创建工作队列
  // 创建并启动工作线程,核心线程池数量是多少就创建多少个工作线程实例
  // 设置线程池中允许创建的线程的最大数量
  for (int i = 1; i <= maxActiveSize; i++) {
   threadIdSet.add(i);
  }
 }

 /**

  * this method used to create a single instance for this Class
  *
  * @return instance
  */
 public static ThreadPool getSingleInstance() {
  if (null == threadPool) {
   threadPool = new ThreadPool();
  }
  return threadPool;
 }

 /** 向工作队列中加入一个新任务,由工作线程去执行该任务 */

 public synchronized void execute(Runnable task) {
  if (task != null) {
   workQueue.addLast(task);// 向队列中加入一个任务

   Iterator<Integer> iter = threadIdSet.iterator();

   if (null != iter && iter.hasNext()) {
    Integer id = iter.next();
    if (this.activeCount() < maxActiveSize) {
     threadIdSet.remove(id);
     printLog("create new work thread " + id);
     new WorkThread(id).start();
    }
   }
   notify(); // 唤醒一个正在getTask()方法中待任务的工作线程
  }
 }

 /**

  * this method used to print run time message when export all report
  * @param msg print message
  */
 private void printLog(String msg) {
  //System.out.println(msg);
 }

 /**

  * 内部类,工作线程,负责从工作队列中取出任务,并执行
  *
  * @author sunnylocus
  */
 private class WorkThread extends Thread {
  private int id;

  public WorkThread(int id) {

   // 父类构造方法,将线程加入到当前ThreadPool线程组中
   super(ThreadPool.this, "Work Thread " + id);
   this.id = id;
  }

  /** 从工作队列中取出一个任务,工作线程会调用此方法,并执行该任务 */

  public void run() {
   while (!isInterrupted()) { // isInterrupted()方法继承自Thread类,判断线程是否被中断
    Runnable task = null;
    // 必须同步工作队列
    synchronized (workQueue) {
     while (workQueue.size() == 0) {
      // destory this active thread
      printLog("no task in the queue, close work thread" + id);
      threadIdSet.add(id);
      return;
     }

     task = workQueue.removeFirst(); // 反回队列中第一个元素,并从队列中删除

    }
    // 如果getTask()返回null或者线程执行getTask()时被中断,则结束此线程
    if (task == null || isInterrupted()) {
     return;
    }
    try {
     printLog("work thread " + id + " begin task...");
     task.run(); // 运行任务
    } catch (Throwable t) {
     t.printStackTrace();
    }

   }// end while

  }// end run
 }// end workThread
}
 

 

 

用法:

  ThreadPool threadPool = ThreadPool.getSingleInstance();

  threadPool.execute(one tread instance);