线程池简介

  多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力。    

  假设一个服务器完成一项任务所需时间为:

  1. T1 创建线程时间
  2. T2 在线程中执行任务的时间
  3. T3 销毁线程时间

  如果:T1 + T3 远大于 T2,则可以采用线程池,以提高服务器性能。

  一个线程池包括以下四个基本组成部分:

  1. 线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;
  2. 工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
  3. 任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
  4. 任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。

  线程池技术正是关注如何缩短或调整T1,T3时间的技术,从而提高服务器程序性能的。

  它把T1,T3分别安排在服务器程序的启动和结束的时间段或者一些空闲的时间段,这样在服务器程序处理客户请求时,不会有T1,T3的开销了。

  线程池不仅调整T1,T3产生的时间段,而且它还显著减少了创建线程的数目,看一个例子:

  假设一个服务器一天要处理50000个请求,并且每个请求需要一个单独的线程完成。在线程池中,线程数一般是固定的,所以产生线程总数不会超过线程池中线程的数目,而如果服务器不利用线程池来处理这些请求则线程总数为50000。一般线程池大小是远小于50000。所以利用线程池的服务器程序不会为了创建50000而在处理请求时浪费时间,从而提高效率。

    代码实现中并没有实现任务接口,而是把Runnable对象加入到线程池管理器(ThreadPool),把剩下的事情交由线程池管理器(ThreadPool)来完成

用Java实现简单的线程池  

  线程池实现

  1 import java.util.List;
  2 import java.util.Vector;
  3 
  4 /**
  5  * 
  6  * @description:线程池
  7  * @author liuchengwei(wwwlllll@126.com)
  8  * @date Sep 19, 2014 10:15:32 PM
  9  */
 10 public class ThreadPool {
 11     private static ThreadPool instance_ = null;
 12     //定义优先级别常数,空闲的线程按照优先级不同分别存放在三个vector中
 13     public static final int LOW_PRIORITY = 0;
 14     public static final int NORMAL_PRIORITY = 1;
 15     public static final int HIGH_PRIORITY = 2;
 16     //保存空闲线程的List,或者说它是"池"
 17     private List<PooledThread>[] idleThreads_;
 18     private boolean shutDown_ = false;
 19     private int threadCreationCounter_; //以创建的线程的个数
 20     private boolean debug_ = false; //是否输出调试信息
 21 
 22     //构造函数,因为这个类视作为singleton实现的,因此构造函数为私有
 23     private ThreadPool() {
 24         // 产生空闲线程.三个vector分别存放分别处在三个优先级的线程的引用
 25         List[] idleThreads = { new Vector(5), new Vector(5), new Vector(5) };
 26         idleThreads_ = idleThreads;
 27         threadCreationCounter_ = 0;
 28     }
 29 
 30     public int getCreatedThreadsCount() {
 31         return threadCreationCounter_;
 32     }
 33 
 34     //通过这个函数得到线程池类的实例
 35     public static ThreadPool instance() {
 36         if (instance_ == null)
 37             instance_ = new ThreadPool();
 38         return instance_;
 39     }
 40 
 41     public boolean isDebug() {
 42         return debug_;
 43     }
 44 
 45     /**
 46      * 
 47      * @description:
 48      * 将线程repoolingThread从新放回到池中,这个方式是同步方法。
 49      * 这个方法会在多线程的环境中调用,设计这个方法的目的是让工作者线程
 50      * 在执行完target中的任务后,调用池类的repool()方法,
 51      * 将线程自身从新放回到池中。只所以这么做是因为线程池并不能预见到
 52      * 工作者线程何时会完成任务。
 53      * @author liuchengwei(wwwlllll@126.com)
 54      * @date Sep 19, 2014 10:15:59 PM
 55      */
 56     protected synchronized void repool(PooledThread repoolingThread) {
 57         if (!shutDown_) {
 58             if (debug_) {
 59                 System.out.println("ThreadPool.repool() : repooling ");
 60             }
 61             switch (repoolingThread.getPriority()) {
 62                 case Thread.MIN_PRIORITY: {
 63                     idleThreads_[LOW_PRIORITY].add(repoolingThread);
 64                     break;
 65                 }
 66                 case Thread.NORM_PRIORITY: {
 67                     idleThreads_[NORMAL_PRIORITY].add(repoolingThread);
 68                     break;
 69                 }
 70                 case Thread.MAX_PRIORITY: {
 71                     idleThreads_[HIGH_PRIORITY].add(repoolingThread);
 72                     break;
 73                 }
 74                 default:
 75                     throw new IllegalStateException("Illegal priority found while repooling a Thread!");
 76             }
 77             notifyAll();//通知所有的线程
 78         }
 79         else {
 80             if (debug_) {
 81                 System.out.println("ThreadPool.repool() : Destroying incoming thread.");
 82             }
 83             repoolingThread.shutDown();//关闭线程
 84         }
 85         if (debug_) {
 86             System.out.println("ThreadPool.recycle() : done.");
 87         }
 88     }
 89 
 90     public void setDebug(boolean newDebug) {
 91         debug_ = newDebug;
 92     }
 93 
 94     //停止池中所有线程
 95     public synchronized void shutdown() {
 96         shutDown_ = true;
 97         if (debug_) {
 98             System.out.println("ThreadPool : shutting down ");
 99         }
100         for (int prioIndex = 0; prioIndex <= HIGH_PRIORITY; prioIndex++) {
101             List prioThreads = idleThreads_[prioIndex];
102             for (int threadIndex = 0; threadIndex < prioThreads.size(); threadIndex++) {
103                 PooledThread idleThread = (PooledThread) prioThreads.get(threadIndex);
104                 idleThread.shutDown();
105             }
106         }
107         notifyAll();
108         if (debug_) {
109             System.out.println("ThreadPool : shutdown done.");
110         }
111     }
112 
113     //以Runnable为target,从池中选择一个优先级为priority的线程创建线程并让线程运行。
114     public synchronized void start(Runnable target, int priority) {
115         PooledThread thread = null; //被选出来执行target的线程
116         List idleList = idleThreads_[priority];
117         if (idleList.size() > 0) {
118             /**
119              * 如果池中相应优先级的线程有空闲的,那么从中取出一个
120              * 设置它的target,并唤醒它
121              * 从空闲的线程队列中获取
122              * 
123              * @author liuchengwei(wwwlllll@126.com)
124              */
125             int lastIndex = idleList.size() - 1;
126             thread = (PooledThread) idleList.get(lastIndex);
127             idleList.remove(lastIndex);
128             thread.setTarget(target);
129         }
130         //池中没有相应优先级的线程
131         else {
132             threadCreationCounter_++;
133             // 创建新线程,
134             thread = new PooledThread(target, "PooledThread #" + threadCreationCounter_, this);
135             // 新线程放入池中
136             switch (priority) {
137                 case LOW_PRIORITY: {
138                     thread.setPriority(Thread.MIN_PRIORITY);
139                     break;
140                 }
141                 case NORMAL_PRIORITY: {
142                     thread.setPriority(Thread.NORM_PRIORITY);
143                     break;
144                 }
145                 case HIGH_PRIORITY: {
146                     thread.setPriority(Thread.MAX_PRIORITY);
147                     break;
148                 }
149                 default: {
150                     thread.setPriority(Thread.NORM_PRIORITY);
151                     break;
152                 }
153             }
154             //启动这个线程
155             thread.start();
156         }
157     }
158 }
View Code

相关文章: