线程池

上一个文章介绍了多线程,现在来说说线程池,写这个文章也是为了自己以后的知识回顾,关于线程池的介绍随处搜索得到都是差不多的,这里也贴一下。
博客园原文:http://www.cnblogs.com/zhongshengzhen/

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

 线程池技术正是关注如何缩短或调整T1,T3时间的技术,从而提高服务器程序性能的。它把T1,T3分别安排在服务器程序的启动和结束的时间段或者一些空闲的时间段,这样在服务器程序处理客户请求时,不会有T1,T3的开销了(T1 创建线程时间,T2 在线程中执行任务的时间,T3 销毁线程时间)。
 
线程池的作用:

线程池作用就是限制系统中执行线程的数量。
根据系统的环境情况,可以自动或手动设置线程数量,达到运行的最佳效果;线程少了浪费系统资源,多了造成系统拥挤效率不高。用线程池控制线程数量,其他线程排队等候。一个任务执行完毕,再从队列的中取最前面的任务开始执行。若队列中没有等待进程,线程池的这一资源处于等待。当一个新任务需要运行时,如果线程池中有等待的工作线程,就可以开始运行了;否则进入等待队列。

 
为什么要用线程池:

1.减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。

2.可以根据系统的承受能力,调整线程池中工作线线程的数目,防止因为消耗过多的内存,而把服务器累趴下(每个线程需要大约1MB内存,线程开的越多消耗的内存也就越大最后死机)。

Java里面线程池的顶级接口是Executor,但是严格意义上讲Executor并不是一个线程池,而只是一个执行线程的工具。真正的线程池接口是ExecutorService。

比较重要的几个类:

ExecutorService

真正的线程池接口。

ScheduledExecutorService

能和Timer/TimerTask类似,解决那些需要任务重复执行的问题。

ThreadPoolExecutor

ExecutorService的默认实现。

ScheduledThreadPoolExecutor

继承ThreadPoolExecutor的ScheduledExecutorService接口实现,周期性任务调度的类实现。

常见线程池:
1. newSingleThreadExecutor
创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。
 
2.newFixedThreadPool
创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。
 
3. newCachedThreadPool
创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲( 60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。
 

4.newScheduledThreadPool

创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。

 
重要的构造函数参数说明:
 
new ThreadPoolExecutor(corePoolSizemaximumPoolSizekeepAliveSecond, TimeUnit.SECONDS , new LinkedBlockingQueue<Runnable>());
 
corePoolSize:核心池的大小,这个参数跟后面讲述的线程池的实现原理有非常大的关系。在创建了线程池后,默认情况下,线程池中并没有任何线程,而是等待有任务到来才创建线程去执行任务,除非调用了prestartAllCoreThreads()或者prestartCoreThread()方法,从这2个方法的名字就可以看出,是预创建线程的意思,即在没有任务到来之前就创建corePoolSize个线程或者一个线程。默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中。
 
maximumPoolSize:线程池最大线程数,这个参数也是一个非常重要的参数,它表示在线程池中最多能创建多少个线程。
 
keepAliveTime:表示线程没有任务执行时最多保持多久时间会终止。默认情况下,只有当线程池中的线程数大于corePoolSize时,keepAliveTime才会起作用,直到线程池中的线程数不大于corePoolSize,即当线程池中的线程数大于corePoolSize时,如果一个线程空闲的时间达到keepAliveTime,则会终止,直到线程池中的线程数不超过corePoolSize。但是如果调用了allowCoreThreadTimeOut(boolean)方法,在线程池中的线程数不大于corePoolSize时,keepAliveTime参数也会起作用,直到线程池中的线程数为0。
 
常规维持 corePoolSize个线程大小,当超过这个 corePoolSize值后会增加到 maximumPoolSize的大小,再多的线程进入只能等待了。
 
测试实例:
 
一、创建固定大小的线程池
SimpleThreadPool.java
 
import  java.util.concurrent.LinkedBlockingQueue;
import  java.util.concurrent.ThreadPoolExecutor;
import  java.util.concurrent.TimeUnit;
 
public  class  SingleThreadPool  extends  ThreadPoolExecutor{
 
      public  SingleThreadPool ( int  corePoolSize,  int  maximumPoolSize,  long  keepAliveSecond) {
             super (corePoolSize, maximumPoolSize, keepAliveSecond, TimeUnit. SECONDS ,  new  LinkedBlockingQueue<Runnable>());
     }
 
}
 
 
SimpleThreadPoolUtil.java
 
public  class  SimpleThreadPoolUtil {
      private  static  int  count  = Runtime.getRuntime().availableProcessors();
     
      public  static  SimpleThreadPool  threadPool  =  new  SimpleThreadPool( count ,  count  , 10);
 
      public  static  void  execute(Runnable task){
             threadPool .execute(task);
     }
}
 
ThreadPoolTest.java
public  class  ThreadPoolTest {
     
      public  static  void  main(String[] args){
           
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(2, "1st" ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(3, "2nd" ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(4, "3rd" ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(5, "4th" ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(6, "5th" ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(7, "6th" ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(8, "7th" ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(9, "8th" ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(10, "9th"  ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(11, "10th"  ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(12, "11th"  ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(13, "12th"  ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(14, "13th"  ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(15, "14th"  ));
           SimpleThreadPoolUtil. execute( new  SimpleThreadTest(0, "15th"  ));
           
     }    
}
class  SimpleThreadTest  implements  Runnable{
      private  int  index ;
      private  String  name ;
      public  SimpleThreadTest(  int  index, String name){
             this .  index  = index;
             this .  name  = name;
     }
      @Override
      public  void  run() {
             int  result = 1;
             for (  int  i=1;i<  index ;i++)
                result = result*i;
           
          System.  out .println(  name +  ":" +  "ActiveCount:" +SimpleThreadPoolUtil.  threadPool .getActiveCount()+
                       "\tTaskCount:" +SimpleThreadPoolUtil.  threadPool .getTaskCount()+  "\t" +Thread. currentThread()+ "\tresult=" +result);
     }
}
###########运行结果################
1st:ActiveCount:3    TaskCount:4     Thread[pool-1-thread-1,5,main]  result=1
4th:ActiveCount:4    TaskCount:15     Thread[pool-1-thread-4,5,main]  result=24
3rd:ActiveCount:3    TaskCount:15     Thread[pool-1-thread-3,5,main]  result=6
2nd:ActiveCount:3    TaskCount:9     Thread[pool-1-thread-2,5,main]  result=2
6th:ActiveCount:4    TaskCount:15     Thread[pool-1-thread-4,5,main]  result=720
8th:ActiveCount:4    TaskCount:15     Thread[pool-1-thread-2,5,main]  result=40320
9th:ActiveCount:4    TaskCount:15     Thread[pool-1-thread-4,5,main]  result=362880
10th:ActiveCount:4   TaskCount:15     Thread[pool-1-thread-2,5,main]  result=3628800
5th:ActiveCount:4    TaskCount:15     Thread[pool-1-thread-1,5,main]  result=120
12th:ActiveCount:4   TaskCount:15     Thread[pool-1-thread-2,5,main]  result=479001600
13th:ActiveCount:4   TaskCount:15     Thread[pool-1-thread-1,5,main]  result=1932053504
14th:ActiveCount:4   TaskCount:15     Thread[pool-1-thread-2,5,main]  result=1278945280
15th:ActiveCount:4   TaskCount:15     Thread[pool-1-thread-1,5,main]  result=1
11th:ActiveCount:4   TaskCount:15     Thread[pool-1-thread-4,5,main]  result=39916800
7th:ActiveCount:4    TaskCount:15     Thread[pool-1-thread-3,5,main]  result=5040
 
说明:Runtime. getRuntime().availableProcessors();虚拟机的最大可用的处理器数量,当前机器的多线程处理器通道,我的机器获得的值为4。
 
new SimpleThreadPool( countcount, 10);申请一个单线程的线程池。
 
二、创建一个单线程的线程池
 

你可能感兴趣的:(线程池)