Java并发:Executor生命周期

  今日小咸儿来说一下有关Java并发:ThreadPoolExecutor类的源码。

  首先来了解一下Executor的生命周期:

  线程池Executor是异步的执行任务,因此任何时刻不能够直接获取提交的任务状态。这些任务有可能已经完成,有可能正在执行或者还在排队等待执行。因此关闭线程池可能会出现以下两种情况:

  • 平缓关闭:已经启动的任务全部执行完毕,同时不再接受新任务—showdown()
  • 立即关闭:取消所有正在执行和未执行的任务—showdownNow()

  那在ThreadPoolExecutor类中的源码是怎么介绍的呢?

  线程池的生命周期为RUNNING、SHUTDOWN、STOP、TIDYING、TERMINATED五种状态。

	 * The runState provides the main lifecycle control, taking on values:
     *
     *   RUNNING:  Accept new tasks and process queued tasks
     *   SHUTDOWN: Don't accept new tasks, but process queued tasks
     *   STOP:     Don't accept new tasks, don't process queued tasks,
     *             and interrupt in-progress tasks
     *   TIDYING:  All tasks have terminated, workerCount is zero,
     *             the thread transitioning to state TIDYING
     *             will run the terminated() hook method
     *   TERMINATED: terminated() has completed
     *
     * The numerical order among these values matters, to allow
     * ordered comparisons. The runState monotonically increases over
     * time, but need not hit each state. The transitions are:
     *
     * RUNNING -> SHUTDOWN
     *    On invocation of shutdown(), perhaps implicitly in finalize()
     * (RUNNING or SHUTDOWN) -> STOP
     *    On invocation of shutdownNow()
     * SHUTDOWN -> TIDYING
     *    When both queue and pool are empty
     * STOP -> TIDYING
     *    When pool is empty
     * TIDYING -> TERMINATED
     *    When the terminated() hook method has completed
     *
     * Threads waiting in awaitTermination() will return when the
     * state reaches TERMINATED.

解析:

RUNNING:接受新的任务并处理队列中的任务
  调用shutdown()方法线程池的状态则由RUNNING–>SHUTDOWN

SHUTDOWN:不接收新的任务,但是处理队列中的任务
STOP:不接收新的任务,不处理队列中的任务,同时中断处理中的任务
  调用shutdownNow()方法线程池状态由RUNNING或者SHUTDOWN状态–>STOP状态

TIDYING:所有的任务处理完,有效的线程数是0
  当任务队列和线程池均为空的时候,线程池的状态由SHUTDOWN -> TIDYING
  当线程池为空时,线程池的状态由STOP -> TIDYING

TERMINATED:terminated()方法执行完毕
  当terminated()方法被调用完成之后,线程池的状态由TIDYING -> TERMINATED

  转换成TIDYING状态的线程会运行terminated()方法,执行完terminated()方法之后,所有等待在awaitTerminated()就会返回。

转换过程:

Java并发:Executor生命周期_第1张图片
  有关于线程池的生命周期认知就到这里,接下来会继续深入理解学习。

你可能感兴趣的:(¤JAVA¤)