当前位置: 移动技术网 > IT编程>开发语言>Java > 深入理解Java编程线程池的实现原理

深入理解Java编程线程池的实现原理

2019年07月19日  | 移动技术网IT编程  | 我要评论

在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题:

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

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

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

以下是本文的目录大纲:

一.java中的threadpoolexecutor类

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

三.使用示例

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

若有不正之处请多多谅解,并欢迎批评指正。

一.java中的threadpoolexecutor类

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

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

public class threadpoolexecutor extends abstractexecutorservice {
  .....
  public threadpoolexecutor(int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,
      blockingqueue<runnable> workqueue);
 
  public threadpoolexecutor(int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,
      blockingqueue<runnable> workqueue,threadfactory threadfactory);
 
  public threadpoolexecutor(int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,
      blockingqueue<runnable> workqueue,rejectedexecutionhandler handler);
 
  public threadpoolexecutor(int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,
    blockingqueue<runnable> workqueue,threadfactory threadfactory,rejectedexecutionhandler handler);
  ...
}

从上面的代码可以得知,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的实现:

public abstract class abstractexecutorservice implements executorservice {
 
  protected <t> runnablefuture<t> newtaskfor(runnable runnable, t value) { };
  protected <t> runnablefuture<t> newtaskfor(callable<t> callable) { };
  public future<?> submit(runnable task) {};
  public <t> future<t> submit(runnable task, t result) { };
  public <t> future<t> submit(callable<t> task) { };
  private <t> t doinvokeany(collection<? extends callable<t>> tasks,
              boolean timed, long nanos)
    throws interruptedexception, executionexception, timeoutexception {
  };
  public <t> t invokeany(collection<? extends callable<t>> tasks)
    throws interruptedexception, executionexception {
  };
  public <t> t invokeany(collection<? extends callable<t>> tasks,
              long timeout, timeunit unit)
    throws interruptedexception, executionexception, timeoutexception {
  };
  public <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks)
    throws interruptedexception {
  };
  public <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks,
                     long timeout, timeunit unit)
    throws interruptedexception {
  };
}

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

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

public interface executorservice extends executor {
 
  void shutdown();
  boolean isshutdown();
  boolean isterminated();
  boolean awaittermination(long timeout, timeunit unit)
    throws interruptedexception;
  <t> future<t> submit(callable<t> task);
  <t> future<t> submit(runnable task, t result);
  future<?> submit(runnable task);
  <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks)
    throws interruptedexception;
  <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks,
                 long timeout, timeunit unit)
    throws interruptedexception;
 
  <t> t invokeany(collection<? extends callable<t>> tasks)
    throws interruptedexception, executionexception;
  <t> t invokeany(collection<? extends callable<t>> tasks,
          long timeout, timeunit unit)
    throws interruptedexception, executionexception, timeoutexception;
}

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

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

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

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

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

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

然后threadpoolexecutor继承了类abstractexecutorservice。

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

execute()
submit()
shutdown()
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变量表示线程池的各个状态:

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

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

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

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

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

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

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

2.任务的执行

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

private final blockingqueue<runnable> workqueue;       //任务缓存队列,用来存放等待执行的任务
private final reentrantlock mainlock = new reentrantlock();  //线程池的主要状态锁,对线程池状态(比如线程池大小
                               //、runstate等)的改变都要使用这个锁
private final hashset<worker> workers = new hashset<worker>(); //用来存放工作集
 
private volatile long keepalivetime;  //线程存货时间  
private volatile boolean allowcorethreadtimeout;  //是否允许为核心线程设置存活时间
private volatile int  corepoolsize;   //核心池的大小(即线程池中的线程数目大于这个参数时,提交的任务会被放进任务缓存队列)
private volatile int  maximumpoolsize;  //线程池最大能容忍的线程数
 
private volatile int  poolsize;    //线程池中当前的线程数
 
private volatile rejectedexecutionhandler handler; //任务拒绝策略
 
private volatile threadfactory threadfactory;  //线程工厂,用来创建线程
 
private int largestpoolsize;  //用来记录线程池中曾经出现过的最大线程数
 
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()方法的实现原理即可:

public void execute(runnable command) {
  if (command == null)
    throw new nullpointerexception();
  if (poolsize >= corepoolsize || !addifundercorepoolsize(command)) {
    if (runstate == running && workqueue.offer(command)) {
      if (runstate != running || poolsize == 0)
        ensurequeuedtaskhandled(command);
    }
    else if (!addifundermaximumpoolsize(command))
      reject(command); // is shutdown or saturated
  }
}

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

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

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

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

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

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

addifundercorepoolsize(command)

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

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

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

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

addifundermaximumpoolsize(command)

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

回到前面:

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

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

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

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

ensurequeuedtaskhandled(command)

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

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

private boolean addifundercorepoolsize(runnable firsttask) {
  thread t = null;
  final reentrantlock mainlock = this.mainlock;
  mainlock.lock();
  try {
    if (poolsize < corepoolsize && runstate == running)
      t = addthread(firsttask);    //创建线程去执行firsttask任务  
    } finally {
    mainlock.unlock();
  }
  if (t == null)
    return false;
  t.start();
  return true;
}

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

t = addthread(firsttask);

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

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

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

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

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

private final class worker implements runnable {
  private final reentrantlock runlock = new reentrantlock();
  private runnable firsttask;
  volatile long completedtasks;
  thread thread;
  worker(runnable firsttask) {
    this.firsttask = firsttask;
  }
  boolean isactive() {
    return runlock.islocked();
  }
  void interruptifidle() {
    final reentrantlock runlock = this.runlock;
    if (runlock.trylock()) {
      try {
    if (thread != thread.currentthread())
    thread.interrupt();
      } finally {
        runlock.unlock();
      }
    }
  }
  void interruptnow() {
    thread.interrupt();
  }
 
  private void runtask(runnable task) {
    final reentrantlock runlock = this.runlock;
    runlock.lock();
    try {
      if (runstate < stop &&
        thread.interrupted() &&
        runstate >= stop)
      boolean ran = false;
      beforeexecute(thread, task);  //beforeexecute方法是threadpoolexecutor类的一个方法,没有具体实现,用户可以根据
      //自己需要重载这个方法和后面的afterexecute方法来进行一些统计信息,比如某个任务的执行时间等      
      try {
        task.run();
        ran = true;
        afterexecute(task, null);
        ++completedtasks;
      } catch (runtimeexception ex) {
        if (!ran)
          afterexecute(task, ex);
        throw ex;
      }
    } finally {
      runlock.unlock();
    }
  }
 
  public void run() {
    try {
      runnable task = firsttask;
      firsttask = null;
      while (task != null || (task = gettask()) != null) {
        runtask(task);
        task = null;
      }
    } finally {
      workerdone(this);  //当任务队列中没有任务时,进行清理工作    
    }
  }
}

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

thread t = new thread(w);

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

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

public void run() {
  try {
    runnable task = firsttask;
    firsttask = null;
    while (task != null || (task = gettask()) != null) {
      runtask(task);
      task = null;
    }
  } finally {
    workerdone(this);
  }
}

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

runnable gettask() {
  for (;;) {
    try {
      int state = runstate;
      if (state > shutdown)
        return null;
      runnable r;
      if (state == shutdown) // help drain queue
        r = workqueue.poll();
      else if (poolsize > corepoolsize || allowcorethreadtimeout) //如果线程数大于核心池大小或者允许为核心池线程设置空闲时间,
        //则通过poll取任务,若等待一定的时间取不到任务,则返回null
        r = workqueue.poll(keepalivetime, timeunit.nanoseconds);
      else
        r = workqueue.take();
      if (r != null)
        return r;
      if (workercanexit()) {  //如果没取到任务,即r为null,则判断当前的worker是否可以退出
        if (runstate >= shutdown) // wake up others
          interruptidleworkers();  //中断处于空闲状态的worker
        return null;
      }
      // else retry
    } catch (interruptedexception ie) {
      // on interruption, re-check runstate
    }
  }

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

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

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

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

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

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

void interruptidleworkers() {
  final reentrantlock mainlock = this.mainlock;
  mainlock.lock();
  try {
    for (worker w : workers) //实际上调用的是worker的interruptifidle()方法
      w.interruptifidle();
  } finally {
    mainlock.unlock();
  }
}

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

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

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

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

private boolean addifundermaximumpoolsize(runnable firsttask) {
  thread t = null;
  final reentrantlock mainlock = this.mainlock;
  mainlock.lock();
  try {
    if (poolsize < maximumpoolsize && runstate == running)
      t = addthread(firsttask);
  } finally {
    mainlock.unlock();
  }
  if (t == null)
    return false;
  t.start();
  return true;
}

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

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

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

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

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

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

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

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

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

prestartcorethread():初始化一个核心线程;
prestartallcorethreads():初始化所有核心线程
下面是这2个方法的实现:

public boolean prestartcorethread() {
  return addifundercorepoolsize(null); //注意传进去的参数是null
}
 
public int prestartallcorethreads() {
  int n = 0;
  while (addifundercorepoolsize(null))//注意传进去的参数是null
    ++n;
  return n;
}

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

r = workqueue.take();

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

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

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

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

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

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

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

5.任务拒绝策略

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

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

6.线程池的关闭

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

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

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

setcorepoolsize:设置核心池大小
setmaximumpoolsize:设置线程池最大能创建的线程数目大小
当上述参数从小变大时,threadpoolexecutor进行线程赋值,还可能立即创建新的线程来执行任务。

三.使用示例

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

public class test {
   public static void main(string[] args) {  
     threadpoolexecutor executor = new threadpoolexecutor(5, 10, 200, timeunit.milliseconds,
         new arrayblockingqueue<runnable>(5));
 
     for(int i=0;i<15;i++){
       mytask mytask = new mytask(i);
       executor.execute(mytask);
       system.out.println("线程池中线程数目:"+executor.getpoolsize()+",队列中等待执行的任务数目:"+
       executor.getqueue().size()+",已执行玩别的任务数目:"+executor.getcompletedtaskcount());
     }
     executor.shutdown();
   }
}
 
class mytask implements runnable {
  private int tasknum;
 
  public mytask(int num) {
    this.tasknum = num;
  }
 
  @override
  public void run() {
    system.out.println("正在执行task "+tasknum);
    try {
      thread.currentthread().sleep(4000);
    } catch (interruptedexception e) {
      e.printstacktrace();
    }
    system.out.println("task "+tasknum+"执行完毕");
  }
}

执行结果:

正在执行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执行完毕

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

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

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

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

public static executorservice newfixedthreadpool(int nthreads) {
  return new threadpoolexecutor(nthreads, nthreads,
                 0l, timeunit.milliseconds,
                 new linkedblockingqueue<runnable>());
}
public static executorservice newsinglethreadexecutor() {
  return new finalizabledelegatedexecutorservice
    (new threadpoolexecutor(1, 1,
                0l, timeunit.milliseconds,
                new linkedblockingqueue<runnable>()));
}
public static executorservice newcachedthreadpool() {
  return new threadpoolexecutor(0, integer.max_value,
                 60l, timeunit.seconds,
                 new synchronousqueue<runnable>());
}

从它们的具体实现来看,它们实际上也是调用了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

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

总结

以上就是本文关于深入理解java编程线程池的实现原理的全部内容,希望对大家有所帮助。有什么问题可以随时留言,小编会及时回复大家的。感谢朋友们对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网