当前位置: 移动技术网 > IT编程>开发语言>Java > Java并发编程:线程池的使用

Java并发编程:线程池的使用

2018年11月27日  | 移动技术网IT编程  | 我要评论
Java并发编程:线程池的使用 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间。 那么有没有一种办法使得线程可以复用,就是执行完一个任务,并不被销毁,而是可以继续执行其他的任务? 在Java中可以通过 ...

                  java并发编程:线程池的使用

 

  如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间。

  那么有没有一种办法使得线程可以复用,就是执行完一个任务,并不被销毁,而是可以继续执行其他的任务?

  在java中可以通过线程池来达到这样的效果。今天我们就来详细讲解一下java的线程池,首先我们从最核心的threadpoolexecutor类中的方法讲起,然后再讲述它的实现原理,接着给出了它的使用示例,最后讨论了一下如何合理配置线程池的大小。

  以下是本文的目录大纲:

  一.java中的threadpoolexecutor类

  二.深入剖析线程池实现原理

  三.使用示例

  四.如何合理配置线程池的大小  

一.java中的threadpoolexecutor类

  java.uitl.concurrent.threadpoolexecutor类是线程池中最核心的一个类,因此如果要透彻地了解java中的线程池,必须先了解这个类。下面我们来看一下threadpoolexecutor类的具体实现源码。

  在threadpoolexecutor类中提供了四个构造方法:

 1 public class threadpoolexecutor extends abstractexecutorservice {
 2     .....
 3     public threadpoolexecutor(int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,
 4             blockingqueue<runnable> workqueue);
 5  
 6     public threadpoolexecutor(int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,
 7             blockingqueue<runnable> workqueue,threadfactory threadfactory);
 8  
 9     public threadpoolexecutor(int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,
10             blockingqueue<runnable> workqueue,rejectedexecutionhandler handler);
11  
12     public threadpoolexecutor(int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,
13         blockingqueue<runnable> workqueue,threadfactory threadfactory,rejectedexecutionhandler handler);
14     ...
15 }

 

  从上面的代码可以得知,threadpoolexecutor继承了abstractexecutorservice类,并提供了四个构造器,事实上,通过观察每个构造器的源码具体实现,发现前面三个构造器都是调用的第四个构造器进行的初始化工作。

   下面解释下一下构造器中各个参数的含义:

  • corepoolsize:核心池的大小,这个参数跟后面讲述的线程池的实现原理有非常大的关系。在创建了线程池后,默认情况下,线程池中并没有任何线程,而是等待有任务到来才创建线程去执行任务,除非调用了prestartallcorethreads()或者prestartcorethread()方法,从这2个方法的名字就可以看出,是预创建线程的意思,即在没有任务到来之前就创建corepoolsize个线程或者一个线程。默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,当线程池中的线程数目达到corepoolsize后,就会把到达的任务放到缓存队列当中;
  • maximumpoolsize:线程池最大线程数,这个参数也是一个非常重要的参数,它表示在线程池中最多能创建多少个线程;
  • keepalivetime:表示线程没有任务执行时最多保持多久时间会终止。默认情况下,只有当线程池中的线程数大于corepoolsize时,keepalivetime才会起作用,直到线程池中的线程数不大于corepoolsize,即当线程池中的线程数大于corepoolsize时,如果一个线程空闲的时间达到keepalivetime,则会终止,直到线程池中的线程数不超过corepoolsize。但是如果调用了allowcorethreadtimeout(boolean)方法,在线程池中的线程数不大于corepoolsize时,keepalivetime参数也会起作用,直到线程池中的线程数为0;
  • unit:参数keepalivetime的时间单位,有7种取值,在timeunit类中有7种静态属性:
timeunit.days;               //天
timeunit.hours;             //小时
timeunit.minutes;           //分钟
timeunit.seconds;           //秒
timeunit.milliseconds;      //毫秒
timeunit.microseconds;      //微妙
timeunit.nanoseconds;       //纳秒
  • workqueue:一个阻塞队列,用来存储等待执行的任务,这个参数的选择也很重要,会对线程池的运行过程产生重大影响,一般来说,这里的阻塞队列有以下几种选择:
arrayblockingqueue;
linkedblockingqueue;
synchronousqueue;

  arrayblockingqueue和priorityblockingqueue使用较少,一般使用linkedblockingqueue和synchronous。线程池的排队策略与blockingqueue有关。

  • threadfactory:线程工厂,主要用来创建线程;
  • handler:表示当拒绝处理任务时的策略,有以下四种取值:
threadpoolexecutor.abortpolicy:丢弃任务并抛出rejectedexecutionexception异常。 
threadpoolexecutor.discardpolicy:也是丢弃任务,但是不抛出异常。 
threadpoolexecutor.discardoldestpolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
threadpoolexecutor.callerrunspolicy:由调用线程处理该任务 

   具体参数的配置与线程池的关系将在下一节讲述。

  从上面给出的threadpoolexecutor类的代码可以知道,threadpoolexecutor继承了abstractexecutorservice,我们来看一下abstractexecutorservice的实现:

 1 public abstract class abstractexecutorservice implements executorservice {
 2  
 3      
 4     protected <t> runnablefuture<t> newtaskfor(runnable runnable, t value) { };
 5     protected <t> runnablefuture<t> newtaskfor(callable<t> callable) { };
 6     public future<?> submit(runnable task) {};
 7     public <t> future<t> submit(runnable task, t result) { };
 8     public <t> future<t> submit(callable<t> task) { };
 9     private <t> t doinvokeany(collection<? extends callable<t>> tasks,
10                             boolean timed, long nanos)
11         throws interruptedexception, executionexception, timeoutexception {
12     };
13     public <t> t invokeany(collection<? extends callable<t>> tasks)
14         throws interruptedexception, executionexception {
15     };
16     public <t> t invokeany(collection<? extends callable<t>> tasks,
17                            long timeout, timeunit unit)
18         throws interruptedexception, executionexception, timeoutexception {
19     };
20     public <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks)
21         throws interruptedexception {
22     };
23     public <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks,
24                                          long timeout, timeunit unit)
25         throws interruptedexception {
26     };
27 }

 

 abstractexecutorservice是一个抽象类,它实现了executorservice接口。

  我们接着看executorservice接口的实现:

 1 public interface executorservice extends executor {
 2  
 3     void shutdown();
 4     boolean isshutdown();
 5     boolean isterminated();
 6     boolean awaittermination(long timeout, timeunit unit)
 7         throws interruptedexception;
 8     <t> future<t> submit(callable<t> task);
 9     <t> future<t> submit(runnable task, t result);
10     future<?> submit(runnable task);
11     <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks)
12         throws interruptedexception;
13     <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks,
14                                   long timeout, timeunit unit)
15         throws interruptedexception;
16  
17     <t> t invokeany(collection<? extends callable<t>> tasks)
18         throws interruptedexception, executionexception;
19     <t> t invokeany(collection<? extends callable<t>> tasks,
20                     long timeout, timeunit unit)
21         throws interruptedexception, executionexception, timeoutexception;
22 }

 

 而executorservice又是继承了executor接口,我们看一下executor接口的实现:

1 public interface executor {
2     void execute(runnable command);
3 }

 

到这里,大家应该明白了threadpoolexecutor、abstractexecutorservice、executorservice和executor几个之间的关系了。

  executor是一个顶层接口,在它里面只声明了一个方法execute(runnable),返回值为void,参数为runnable类型,从字面意思可以理解,就是用来执行传进去的任务的;

  然后executorservice接口继承了executor接口,并声明了一些方法:submit、invokeall、invokeany以及shutdown等;

  抽象类abstractexecutorservice实现了executorservice接口,基本实现了executorservice中声明的所有方法;

  然后threadpoolexecutor继承了类abstractexecutorservice。

  在threadpoolexecutor类中有几个非常重要的方法:

1 execute()
2 submit()
3 shutdown()
4 shutdownnow()

 

 

   execute()方法实际上是executor中声明的方法,在threadpoolexecutor进行了具体的实现,这个方法是threadpoolexecutor的核心方法,通过这个方法可以向线程池提交一个任务,交由线程池去执行。

  submit()方法是在executorservice中声明的方法,在abstractexecutorservice就已经有了具体的实现,在threadpoolexecutor中并没有对其进行重写,这个方法也是用来向线程池提交任务的,但是它和execute()方法不同,它能够返回任务执行的结果,去看submit()方法的实现,会发现它实际上还是调用的execute()方法,只不过它利用了future来获取任务执行结果(future相关内容将在下一篇讲述)。

  shutdown()和shutdownnow()是用来关闭线程池的。

  还有很多其他的方法:

  比如:getqueue() 、getpoolsize() 、getactivecount()、getcompletedtaskcount()等获取与线程池相关属性的方法,有兴趣的朋友可以自行查阅api。

二.深入剖析线程池实现原理

  在上一节我们从宏观上介绍了threadpoolexecutor,下面我们来深入解析一下线程池的具体实现原理,将从下面几个方面讲解:

  1.线程池状态

  2.任务的执行

  3.线程池中的线程初始化

  4.任务缓存队列及排队策略

  5.任务拒绝策略

  6.线程池的关闭

  7.线程池容量的动态调整

 

1.线程池状态

  在threadpoolexecutor中定义了一个volatile变量,另外定义了几个static final变量表示线程池的各个状态:

1 volatile int runstate;
2 static final int running    = 0;
3 static final int shutdown   = 1;
4 static final int stop       = 2;
5 static final int terminated = 3;

 

   runstate表示当前线程池的状态,它是一个volatile变量用来保证线程之间的可见性;

  下面的几个static final变量表示runstate可能的几个取值。

  当创建线程池后,初始时,线程池处于running状态;

  如果调用了shutdown()方法,则线程池处于shutdown状态,此时线程池不能够接受新的任务,它会等待所有任务执行完毕;

  如果调用了shutdownnow()方法,则线程池处于stop状态,此时线程池不能接受新的任务,并且会去尝试终止正在执行的任务;

  当线程池处于shutdown或stop状态,并且所有工作线程已经销毁,任务缓存队列已经清空或执行结束后,线程池被设置为terminated状态。

2.任务的执行

  在了解将任务提交给线程池到任务执行完毕整个过程之前,我们先来看一下threadpoolexecutor类中其他的一些比较重要成员变量:

 1 private final blockingqueue<runnable> workqueue;              //任务缓存队列,用来存放等待执行的任务
 2 private final reentrantlock mainlock = new reentrantlock();   //线程池的主要状态锁,对线程池状态(比如线程池大小
 3                                                               //、runstate等)的改变都要使用这个锁
 4 private final hashset<worker> workers = new hashset<worker>();  //用来存放工作集
 5  
 6 private volatile long  keepalivetime;    //线程存货时间   
 7 private volatile boolean allowcorethreadtimeout;   //是否允许为核心线程设置存活时间
 8 private volatile int   corepoolsize;     //核心池的大小(即线程池中的线程数目大于这个参数时,提交的任务会被放进任务缓存队列)
 9 private volatile int   maximumpoolsize;   //线程池最大能容忍的线程数
10  
11 private volatile int   poolsize;       //线程池中当前的线程数
12  
13 private volatile rejectedexecutionhandler handler; //任务拒绝策略
14  
15 private volatile threadfactory threadfactory;   //线程工厂,用来创建线程
16  
17 private int largestpoolsize;   //用来记录线程池中曾经出现过的最大线程数
18  
19 private long completedtaskcount;   //用来记录已经执行完毕的任务个数

 

 

   每个变量的作用都已经标明出来了,这里要重点解释一下corepoolsize、maximumpoolsize、largestpoolsize三个变量。

  corepoolsize在很多地方被翻译成核心池大小,其实我的理解这个就是线程池的大小。举个简单的例子:

  假如有一个工厂,工厂里面有10个工人,每个工人同时只能做一件任务。

  因此只要当10个工人中有工人是空闲的,来了任务就分配给空闲的工人做;

  当10个工人都有任务在做时,如果还来了任务,就把任务进行排队等待;

  如果说新任务数目增长的速度远远大于工人做任务的速度,那么此时工厂主管可能会想补救措施,比如重新招4个临时工人进来;

  然后就将任务也分配给这4个临时工人做;

  如果说着14个工人做任务的速度还是不够,此时工厂主管可能就要考虑不再接收新的任务或者抛弃前面的一些任务了。

  当这14个工人当中有人空闲时,而新任务增长的速度又比较缓慢,工厂主管可能就考虑辞掉4个临时工了,只保持原来的10个工人,毕竟请额外的工人是要花钱的。

 

  这个例子中的corepoolsize就是10,而maximumpoolsize就是14(10+4)。

  也就是说corepoolsize就是线程池大小,maximumpoolsize在我看来是线程池的一种补救措施,即任务量突然过大时的一种补救措施。

  不过为了方便理解,在本文后面还是将corepoolsize翻译成核心池大小。

  largestpoolsize只是一个用来起记录作用的变量,用来记录线程池中曾经有过的最大线程数目,跟线程池的容量没有任何关系。

 

  下面我们进入正题,看一下任务从提交到最终执行完毕经历了哪些过程。

  在threadpoolexecutor类中,最核心的任务提交方法是execute()方法,虽然通过submit也可以提交任务,但是实际上submit方法里面最终调用的还是execute()方法,所以我们只需要研究execute()方法的实现原理即可:

 1 public void execute(runnable command) {
 2     if (command == null)
 3         throw new nullpointerexception();
 4     if (poolsize >= corepoolsize || !addifundercorepoolsize(command)) {
 5         if (runstate == running && workqueue.offer(command)) {
 6             if (runstate != running || poolsize == 0)
 7                 ensurequeuedtaskhandled(command);
 8         }
 9         else if (!addifundermaximumpoolsize(command))
10             reject(command); // is shutdown or saturated
11     }
12 }

 

 

   上面的代码可能看起来不是那么容易理解,下面我们一句一句解释:

  首先,判断提交的任务command是否为null,若是null,则抛出空指针异常;

  接着是这句,这句要好好理解一下:

1 if (poolsize >= corepoolsize || !addifundercorepoolsize(command))

 

   由于是或条件运算符,所以先计算前半部分的值,如果线程池中当前线程数不小于核心池大小,那么就会直接进入下面的if语句块了。

  如果线程池中当前线程数小于核心池大小,则接着执行后半部分,也就是执行

1 addifundercorepoolsize(command)

  如果执行完addifundercorepoolsize这个方法返回false,则继续执行下面的if语句块,否则整个方法就直接执行完毕了。

  如果执行完addifundercorepoolsize这个方法返回false,然后接着判断:

1 if (runstate == running && workqueue.offer(command))

 

   如果当前线程池处于running状态,则将任务放入任务缓存队列;如果当前线程池不处于running状态或者任务放入缓存队列失败,则执行:

1 addifundermaximumpoolsize(command)

 

  如果执行addifundermaximumpoolsize方法失败,则执行reject()方法进行任务拒绝处理。

  回到前面:

1 if (runstate == running && workqueue.offer(command))

 

   这句的执行,如果说当前线程池处于running状态且将任务放入任务缓存队列成功,则继续进行判断:

1 if (runstate != running || poolsize == 0)

 

   这句判断是为了防止在将此任务添加进任务缓存队列的同时其他线程突然调用shutdown或者shutdownnow方法关闭了线程池的一种应急措施。如果是这样就执行:

1 ensurequeuedtaskhandled(command)

 

   进行应急处理,从名字可以看出是保证 添加到任务缓存队列中的任务得到处理。

  我们接着看2个关键方法的实现:addifundercorepoolsize和addifundermaximumpoolsize:

 1 private boolean addifundercorepoolsize(runnable firsttask) {
 2     thread t = null;
 3     final reentrantlock mainlock = this.mainlock;
 4     mainlock.lock();
 5     try {
 6         if (poolsize < corepoolsize && runstate == running)
 7             t = addthread(firsttask);        //创建线程去执行firsttask任务   
 8         } finally {
 9         mainlock.unlock();
10     }
11     if (t == null)
12         return false;
13     t.start();
14     return true;
15 }

 

   这个是addifundercorepoolsize方法的具体实现,从名字可以看出它的意图就是当低于核心吃大小时执行的方法。下面看其具体实现,首先获取到锁,因为这地方涉及到线程池状态的变化,先通过if语句判断当前线程池中的线程数目是否小于核心池大小,有朋友也许会有疑问:前面在execute()方法中不是已经判断过了吗,只有线程池当前线程数目小于核心池大小才会执行addifundercorepoolsize方法的,为何这地方还要继续判断?原因很简单,前面的判断过程中并没有加锁,因此可能在execute方法判断的时候poolsize小于corepoolsize,而判断完之后,在其他线程中又向线程池提交了任务,就可能导致poolsize不小于corepoolsize了,所以需要在这个地方继续判断。然后接着判断线程池的状态是否为running,原因也很简单,因为有可能在其他线程中调用了shutdown或者shutdownnow方法。然后就是执行

1 t = addthread(firsttask);

 

   这个方法也非常关键,传进去的参数为提交的任务,返回值为thread类型。然后接着在下面判断t是否为空,为空则表明创建线程失败(即poolsize>=corepoolsize或者runstate不等于running),否则调用t.start()方法启动线程。

  我们来看一下addthread方法的实现:

 1 private thread addthread(runnable firsttask) {
 2     worker w = new worker(firsttask);
 3     thread t = threadfactory.newthread(w);  //创建一个线程,执行任务   
 4     if (t != null) {
 5         w.thread = t;            //将创建的线程的引用赋值为w的成员变量       
 6         workers.add(w);
 7         int nt = ++poolsize;     //当前线程数加1       
 8         if (nt > largestpoolsize)
 9             largestpoolsize = nt;
10     }
11     return t;
12 }

 

   在addthread方法中,首先用提交的任务创建了一个worker对象,然后调用线程工厂threadfactory创建了一个新的线程t,然后将线程t的引用赋值给了worker对象的成员变量thread,接着通过workers.add(w)将worker对象添加到工作集当中。

  下面我们看一下worker类的实现:

 1 private final class worker implements runnable {
 2     private final reentrantlock runlock = new reentrantlock();
 3     private runnable firsttask;
 4     volatile long completedtasks;
 5     thread thread;
 6     worker(runnable firsttask) {
 7         this.firsttask = firsttask;
 8     }
 9     boolean isactive() {
10         return runlock.islocked();
11     }
12     void interruptifidle() {
13         final reentrantlock runlock = this.runlock;
14         if (runlock.trylock()) {
15             try {
16         if (thread != thread.currentthread())
17         thread.interrupt();
18             } finally {
19                 runlock.unlock();
20             }
21         }
22     }
23     void interruptnow() {
24         thread.interrupt();
25     }
26  
27     private void runtask(runnable task) {
28         final reentrantlock runlock = this.runlock;
29         runlock.lock();
30         try {
31             if (runstate < stop &&
32                 thread.interrupted() &&
33                 runstate >= stop)
34             boolean ran = false;
35             beforeexecute(thread, task);   //beforeexecute方法是threadpoolexecutor类的一个方法,没有具体实现,用户可以根据
36             //自己需要重载这个方法和后面的afterexecute方法来进行一些统计信息,比如某个任务的执行时间等           
37             try {
38                 task.run();
39                 ran = true;
40                 afterexecute(task, null);
41                 ++completedtasks;
42             } catch (runtimeexception ex) {
43                 if (!ran)
44                     afterexecute(task, ex);
45                 throw ex;
46             }
47         } finally {
48             runlock.unlock();
49         }
50     }
51  
52     public void run() {
53         try {
54             runnable task = firsttask;
55             firsttask = null;
56             while (task != null || (task = gettask()) != null) {
57                 runtask(task);
58                 task = null;
59             }
60         } finally {
61             workerdone(this);   //当任务队列中没有任务时,进行清理工作       
62         }
63     }
64 }

 

   它实际上实现了runnable接口,因此上面的thread t = threadfactory.newthread(w);效果跟下面这句的效果基本一样:

1 thread t = new thread(w);

 

   相当于传进去了一个runnable任务,在线程t中执行这个runnable。

  既然worker实现了runnable接口,那么自然最核心的方法便是run()方法了:

 1 public void run() {
 2     try {
 3         runnable task = firsttask;
 4         firsttask = null;
 5         while (task != null || (task = gettask()) != null) {
 6             runtask(task);
 7             task = null;
 8         }
 9     } finally {
10         workerdone(this);
11     }
12 }

 

   从run方法的实现可以看出,它首先执行的是通过构造器传进来的任务firsttask,在调用runtask()执行完firsttask之后,在while循环里面不断通过gettask()去取新的任务来执行,那么去哪里取呢?自然是从任务缓存队列里面去取,gettask是threadpoolexecutor类中的方法,并不是worker类中的方法,下面是gettask方法的实现:

 1 runnable gettask() {
 2     for (;;) {
 3         try {
 4             int state = runstate;
 5             if (state > shutdown)
 6                 return null;
 7             runnable r;
 8             if (state == shutdown)  // help drain queue
 9                 r = workqueue.poll();
10             else if (poolsize > corepoolsize || allowcorethreadtimeout) //如果线程数大于核心池大小或者允许为核心池线程设置空闲时间,
11                 //则通过poll取任务,若等待一定的时间取不到任务,则返回null
12                 r = workqueue.poll(keepalivetime, timeunit.nanoseconds);
13             else
14                 r = workqueue.take();
15             if (r != null)
16                 return r;
17             if (workercanexit()) {    //如果没取到任务,即r为null,则判断当前的worker是否可以退出
18                 if (runstate >= shutdown) // wake up others
19                     interruptidleworkers();   //中断处于空闲状态的worker
20                 return null;
21             }
22             // else retry
23         } catch (interruptedexception ie) {
24             // on interruption, re-check runstate
25         }
26     }
27 }

 

   在gettask中,先判断当前线程池状态,如果runstate大于shutdown(即为stop或者terminated),则直接返回null。

  如果runstate为shutdown或者running,则从任务缓存队列取任务。

  如果当前线程池的线程数大于核心池大小corepoolsize或者允许为核心池中的线程设置空闲存活时间,则调用poll(time,timeunit)来取任务,这个方法会等待一定的时间,如果取不到任务就返回null。

  然后判断取到的任务r是否为null,为null则通过调用workercanexit()方法来判断当前worker是否可以退出,我们看一下workercanexit()的实现:

 1 private boolean workercanexit() {
 2     final reentrantlock mainlock = this.mainlock;
 3     mainlock.lock();
 4     boolean canexit;
 5     //如果runstate大于等于stop,或者任务缓存队列为空了
 6     //或者  允许为核心池线程设置空闲存活时间并且线程池中的线程数目大于1
 7     try {
 8         canexit = runstate >= stop ||
 9             workqueue.isempty() ||
10             (allowcorethreadtimeout &&
11              poolsize > math.max(1, corepoolsize));
12     } finally {
13         mainlock.unlock();
14     }
15     return canexit;
16 }

 

   也就是说如果线程池处于stop状态、或者任务队列已为空或者允许为核心池线程设置空闲存活时间并且线程数大于1时,允许worker退出。如果允许worker退出,则调用interruptidleworkers()中断处于空闲状态的worker,我们看一下interruptidleworkers()的实现:

 1 void interruptidleworkers() {
 2     final reentrantlock mainlock = this.mainlock;
 3     mainlock.lock();
 4     try {
 5         for (worker w : workers)  //实际上调用的是worker的interruptifidle()方法
 6             w.interruptifidle();
 7     } finally {
 8         mainlock.unlock();
 9     }
10 }

 

   从实现可以看出,它实际上调用的是worker的interruptifidle()方法,在worker的interruptifidle()方法中

 1 void interruptifidle() {
 2     final reentrantlock runlock = this.runlock;
 3     if (runlock.trylock()) {    //注意这里,是调用trylock()来获取锁的,因为如果当前worker正在执行任务,锁已经被获取了,是无法获取到锁的
 4                                 //如果成功获取了锁,说明当前worker处于空闲状态
 5         try {
 6     if (thread != thread.currentthread())  
 7     thread.interrupt();
 8         } finally {
 9             runlock.unlock();
10         }
11     }
12 }

 

    这里有一个非常巧妙的设计方式,假如我们来设计线程池,可能会有一个任务分派线程,当发现有线程空闲时,就从任务缓存队列中取一个任务交给空闲线程执行。但是在这里,并没有采用这样的方式,因为这样会要额外地对任务分派线程进行管理,无形地会增加难度和复杂度,这里直接让执行完任务的线程去任务缓存队列里面取任务来执行。

   我们再看addifundermaximumpoolsize方法的实现,这个方法的实现思想和addifundercorepoolsize方法的实现思想非常相似,唯一的区别在于addifundermaximumpoolsize方法是在线程池中的线程数达到了核心池大小并且往任务队列中添加任务失败的情况下执行的:

 1 private boolean addifundermaximumpoolsize(runnable firsttask) {
 2     thread t = null;
 3     final reentrantlock mainlock = this.mainlock;
 4     mainlock.lock();
 5     try {
 6         if (poolsize < maximumpoolsize && runstate == running)
 7             t = addthread(firsttask);
 8     } finally {
 9         mainlock.unlock();
10     }
11     if (t == null)
12         return false;
13     t.start();
14     return true;
15 }

 

   看到没有,其实它和addifundercorepoolsize方法的实现基本一模一样,只是if语句判断条件中的poolsize < maximumpoolsize不同而已。

  到这里,大部分朋友应该对任务提交给线程池之后到被执行的整个过程有了一个基本的了解,下面总结一下:

  1)首先,要清楚corepoolsize和maximumpoolsize的含义;

  2)其次,要知道worker是用来起到什么作用的;

  3)要知道任务提交给线程池之后的处理策略,这里总结一下主要有4点:

  • 如果当前线程池中的线程数目小于corepoolsize,则每来一个任务,就会创建一个线程去执行这个任务;
  • 如果当前线程池中的线程数目>=corepoolsize,则每来一个任务,会尝试将其添加到任务缓存队列当中,若添加成功,则该任务会等待空闲线程将其取出去执行;若添加失败(一般来说是任务缓存队列已满),则会尝试创建新的线程去执行这个任务;
  • 如果当前线程池中的线程数目达到maximumpoolsize,则会采取任务拒绝策略进行处理;
  • 如果线程池中的线程数量大于 corepoolsize时,如果某线程空闲时间超过keepalivetime,线程将被终止,直至线程池中的线程数目不大于corepoolsize;如果允许为核心池中的线程设置存活时间,那么核心池中的线程空闲时间超过keepalivetime,线程也会被终止。

3.线程池中的线程初始化

  默认情况下,创建线程池之后,线程池中是没有线程的,需要提交任务之后才会创建线程。

  在实际中如果需要线程池创建之后立即创建线程,可以通过以下两个方法办到:

  • prestartcorethread():初始化一个核心线程;
  • prestartallcorethreads():初始化所有核心线程

  下面是这2个方法的实现:

 1 public boolean prestartcorethread() {
 2     return addifundercorepoolsize(null); //注意传进去的参数是null
 3 }
 4  
 5 public int prestartallcorethreads() {
 6     int n = 0;
 7     while (addifundercorepoolsize(null))//注意传进去的参数是null
 8         ++n;
 9     return n;
10 }

 

   注意上面传进去的参数是null,根据第2小节的分析可知如果传进去的参数为null,则最后执行线程会阻塞在gettask方法中的

1 r = workqueue.take();

 

  即等待任务队列中有任务。

4.任务缓存队列及排队策略

  在前面我们多次提到了任务缓存队列,即workqueue,它用来存放等待执行的任务。

  workqueue的类型为blockingqueue<runnable>,通常可以取下面三种类型:

  1)arrayblockingqueue:基于数组的先进先出队列,此队列创建时必须指定大小;

  2)linkedblockingqueue:基于链表的先进先出队列,如果创建时没有指定此队列大小,则默认为integer.max_value;

  3)synchronousqueue:这个队列比较特殊,它不会保存提交的任务,而是将直接新建一个线程来执行新来的任务。

5.任务拒绝策略

  当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumpoolsize,如果还有任务到来就会采取任务拒绝策略,通常有以下四种策略:

1 threadpoolexecutor.abortpolicy:丢弃任务并抛出rejectedexecutionexception异常。
2 threadpoolexecutor.discardpolicy:也是丢弃任务,但是不抛出异常。
3 threadpoolexecutor.discardoldestpolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
4 threadpoolexecutor.callerrunspolicy:由调用线程处理该任务

 

6.线程池的关闭

  threadpoolexecutor提供了两个方法,用于线程池的关闭,分别是shutdown()和shutdownnow(),其中:

  • shutdown():不会立即终止线程池,而是要等所有任务缓存队列中的任务都执行完后才终止,但再也不会接受新的任务
  • shutdownnow():立即终止线程池,并尝试打断正在执行的任务,并且清空任务缓存队列,返回尚未执行的任务

7.线程池容量的动态调整

  threadpoolexecutor提供了动态调整线程池容量大小的方法:setcorepoolsize()和setmaximumpoolsize(),

  • setcorepoolsize:设置核心池大小
  • setmaximumpoolsize:设置线程池最大能创建的线程数目大小

  当上述参数从小变大时,threadpoolexecutor进行线程赋值,还可能立即创建新的线程来执行任务。

三.使用示例

  前面我们讨论了关于线程池的实现原理,这一节我们来看一下它的具体使用:

 1 public class test {
 2      public static void main(string[] args) {   
 3          threadpoolexecutor executor = new threadpoolexecutor(5, 10, 200, timeunit.milliseconds,
 4                  new arrayblockingqueue<runnable>(5));
 5           
 6          for(int i=0;i<15;i++){
 7              mytask mytask = new mytask(i);
 8              executor.execute(mytask);
 9              system.out.println("线程池中线程数目:"+executor.getpoolsize()+",队列中等待执行的任务数目:"+
10              executor.getqueue().size()+",已执行玩别的任务数目:"+executor.getcompletedtaskcount());
11          }
12          executor.shutdown();
13      }
14 }
15  
16  
17 class mytask implements runnable {
18     private int tasknum;
19      
20     public mytask(int num) {
21         this.tasknum = num;
22     }
23      
24     @override
25     public void run() {
26         system.out.println("正在执行task "+tasknum);
27         try {
28             thread.currentthread().sleep(4000);
29         } catch (interruptedexception e) {
30             e.printstacktrace();
31         }
32         system.out.println("task "+tasknum+"执行完毕");
33     }
34 }

 

   执行结果:

正在执行task 0
线程池中线程数目:1,队列中等待执行的任务数目:0,已执行玩别的任务数目:0
线程池中线程数目:2,队列中等待执行的任务数目:0,已执行玩别的任务数目:0
正在执行task 1
线程池中线程数目:3,队列中等待执行的任务数目:0,已执行玩别的任务数目:0
正在执行task 2
线程池中线程数目:4,队列中等待执行的任务数目:0,已执行玩别的任务数目:0
正在执行task 3
线程池中线程数目:5,队列中等待执行的任务数目:0,已执行玩别的任务数目:0
正在执行task 4
线程池中线程数目:5,队列中等待执行的任务数目:1,已执行玩别的任务数目:0
线程池中线程数目:5,队列中等待执行的任务数目:2,已执行玩别的任务数目:0
线程池中线程数目:5,队列中等待执行的任务数目:3,已执行玩别的任务数目:0
线程池中线程数目:5,队列中等待执行的任务数目:4,已执行玩别的任务数目:0
线程池中线程数目:5,队列中等待执行的任务数目:5,已执行玩别的任务数目:0
线程池中线程数目:6,队列中等待执行的任务数目:5,已执行玩别的任务数目:0
正在执行task 10
线程池中线程数目:7,队列中等待执行的任务数目:5,已执行玩别的任务数目:0
正在执行task 11
线程池中线程数目:8,队列中等待执行的任务数目:5,已执行玩别的任务数目:0
正在执行task 12
线程池中线程数目:9,队列中等待执行的任务数目:5,已执行玩别的任务数目:0
正在执行task 13
线程池中线程数目:10,队列中等待执行的任务数目:5,已执行玩别的任务数目:0
正在执行task 14
task 3执行完毕
task 0执行完毕
task 2执行完毕
task 1执行完毕
正在执行task 8
正在执行task 7
正在执行task 6
正在执行task 5
task 4执行完毕
task 10执行完毕
task 11执行完毕
task 13执行完毕
task 12执行完毕
正在执行task 9
task 14执行完毕
task 8执行完毕
task 5执行完毕
task 7执行完毕
task 6执行完毕
task 9执行完毕
view code

  从执行结果可以看出,当线程池中线程的数目大于5时,便将任务放入任务缓存队列里面,当任务缓存队列满了之后,便创建新的线程。如果上面程序中,将for循环中改成执行20个任务,就会抛出任务拒绝异常了。

  不过在java doc中,并不提倡我们直接使用threadpoolexecutor,而是使用executors类中提供的几个静态方法来创建线程池:

1 executors.newcachedthreadpool();        //创建一个缓冲池,缓冲池容量大小为integer.max_value
2 executors.newsinglethreadexecutor();   //创建容量为1的缓冲池
3 executors.newfixedthreadpool(int);    //创建固定容量大小的缓冲池

 

  下面是这三个静态方法的具体实现;

 1 public static executorservice newfixedthreadpool(int nthreads) {
 2     return new threadpoolexecutor(nthreads, nthreads,
 3                                   0l, timeunit.milliseconds,
 4                                   new linkedblockingqueue<runnable>());
 5 }
 6 public static executorservice newsinglethreadexecutor() {
 7     return new finalizabledelegatedexecutorservice
 8         (new threadpoolexecutor(1, 1,
 9                                 0l, timeunit.milliseconds,
10                                 new linkedblockingqueue<runnable>()));
11 }
12 public static executorservice newcachedthreadpool() {
13     return new threadpoolexecutor(0, integer.max_value,
14                                   60l, timeunit.seconds,
15                                   new synchronousqueue<runnable>());
16 }

 

从它们的具体实现来看,它们实际上也是调用了threadpoolexecutor,只不过参数都已配置好了。

  newfixedthreadpool创建的线程池corepoolsize和maximumpoolsize值是相等的,它使用的linkedblockingqueue;

  newsinglethreadexecutor将corepoolsize和maximumpoolsize都设置为1,也使用的linkedblockingqueue;

  newcachedthreadpool将corepoolsize设置为0,将maximumpoolsize设置为integer.max_value,使用的synchronousqueue,也就是说来了任务就创建线程运行,当线程空闲超过60秒,就销毁线程。

  实际中,如果executors提供的三个静态方法能满足要求,就尽量使用它提供的三个方法,因为自己去手动配置threadpoolexecutor的参数有点麻烦,要根据实际任务的类型和数量来进行配置。

  另外,如果threadpoolexecutor达不到要求,可以自己继承threadpoolexecutor类进行重写。

四.如何合理配置线程池的大小

  本节来讨论一个比较重要的话题:如何合理配置线程池大小,仅供参考。

  一般需要根据任务的类型来配置线程池大小:

  如果是cpu密集型任务,就需要尽量压榨cpu,参考值可以设为 ncpu+1

  如果是io密集型任务,参考值可以设置为2*ncpu

  当然,这只是一个参考值,具体的设置还需要根据实际情况进行调整,比如可以先将线程池大小设置为参考值,再观察任务运行情况和系统负载、资源利用率来进行适当调整。

  参考资料:

  

  

  

  

  

  

  《jdk api 1.6》

 

原文 : http://www.cnblogs.com/dolphin0520/p/3932921.html

 

 

下面是一段自己的测试代码: (简易)

 1 package com.example.demo;
 2 
 3 import java.util.concurrent.executorservice;
 4 import static java.util.concurrent.executors.*;
 5 
 6 public class executorstest {
 7     
 8     public static void main(string[] args) {
 9        // executorservice cachedthreadpool = newcachedthreadpool();
10        // executorservice cachedthreadpool = newfixedthreadpool(2);
11         executorservice pool = newscheduledthreadpool(2);
12         for (int i = 0; i < 10; i++) {
13             final int index = i;
14 //            try {
15 //                thread.sleep(index * 300);
16 //            } catch (interruptedexception e) {
17 //                e.printstacktrace();
18 //            }
19             pool.execute(new runnable() {
20                 @override
21                 public void run() {
22                     system.out.println(index);
23                     system.out.println(thread.currentthread().getname()+"正在执行......");
24                 }
25             });
26            
27         }
28         pool.shutdown();
29     }
30 }

 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网