J.U.C包 - 线程池ThreadPoolExecutor

Java Concurrent包 - 线程池ThreadPoolExecutor

core and maximux pool sizes

  • 核心线程数(corePoolSize)
  • 最大线程数(maximumPoolSize)
  • 任务队列(workerQueue)

当一个新任务提交后:线程

  • 若正在运行的线程数 < corePoolSize,即便其余工做线程处于空闲状态,也会建立一个新线程来处理这个任务
  • 若 corePoolSize < 正在运行线程数 < maximumPoolSize,则只有在workerQueue已满的状况下才会建立新线程

保持活动时间(Keep-alive times)

若是当前池中线程的数量超过corePoolSize,在这些额外线程中,闲置时间超过keepAliveTime的将会被终止。生命周期

默认状况下,保活策略只有在线程数超过corePoolSize的时候被启用。队列

当allowCoreThreadTimeOut=true时,容许在空闲超时的状况下关闭核心线程ci

队列

任何BlockingQueue能够用来传输和保持提交的任务,这个queue的使用与池的大小有关:it

  • 若运行的线程数 < corePoolSize,Executor会添加新的线程而不是让任务进入队列
  • 若运行的线程数 >= corePoolSize,Executor会让新的任务进入队列而不是建立新的线程
  • 若没法将新的任务加入队列(队满),则建立新的线程,直到池中线程数超过maximumPoolSize,若线程数达到maximumPoolSize,新的任务将会被拒绝

有三大排队策略:io

  • 直接提交:默认为SynchronousQueue
  • 无界队列:好比LinkedBlockingQueue
  • 有界队列:好比ArrayBlockingQueue

任务拒绝

当Executor已经被关闭,或者Executor使用的有界队列容量已经饱和而且已达到最大线程数时,新提交的任务将会被拒绝。在任何一种状况下,execute方法将会调用RejectedExecutionHandler的rejectedExecution方法。thread

线程池的结束(Finalization)

当线程池再也不被程序使用而且没有其余的线程在执行时,将会被自动关闭。线程池

runState

runState提供了主要的生命周期控制,取值范围:transition

  • 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

runState的状态转变:程序

  • 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
相关文章
相关标签/搜索