官方文档
https://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor
如果能好好阅读官方文档,也就不太需要阅读这篇文章了。。。
ThreadPoolExecutors运行图
按照自己对源码的理解,画了一个图,且看且珍惜。。。
带着疑问阅读源码??
- 线程池是如何节省线程频繁创建和销毁的开销的呢??
- 核心线程是如何保持永驻在线程池中呢?
- 非核心线程是如何在keepAliveTime超时后销毁的呢?
- WorkQueue有无边界对线程池处理Runnable有什么影响?初始化线程池时,workQueue可以为非空么?
源码详解
常量详解
不看懂这些,后续代码也很难看懂吧~
/**
* 主池子的控制状态ctl,是一个原子整数,包含两个含义的字段
* workerCount 表示当前有效的线程数
* runState 表示运行状态,是否正在运行、关闭等
* The main pool control state, ctl, is an atomic integer packing
* two conceptual fields
* workerCount, indicating the effective number of threads
* runState, indicating whether running, shutting down etc
*
* 为了将这两个字段打包进一个int,我们限制workerCount在(2^29)-1而不是(2^31)-1
* 如果这在将来是个问题,可以把变量改成AtomicLong类型,并调整移位和掩码常数
* 但是在需要之前,使用int可以使代码更快以及使用更简单。
* In order to pack them into one int, we limit workerCount to
* (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
* billion) otherwise representable. If this is ever an issue in
* the future, the variable can be changed to be an AtomicLong,
* and the shift/mask constants below adjusted. But until the need
* arises, this code is a bit faster and simpler using an int.
*
* workerCount 是当前已经被允许启动并不允许停止的worker数量
* 该值可能与当前实际存活的线程数量不同,举个例子,当一个ThreadFactory创建一个线程失败了,并且即将退出的线程在终止之前仍然在执行。
* 用户可见的pool size就是当前workers的大小。
* The workerCount is the number of workers that have been
* permitted to start and not permitted to stop. The value may be
* transiently different from the actual number of live threads,
* for example when a ThreadFactory fails to create a thread when
* asked, and when exiting threads are still performing
* bookkeeping before terminating. The user-visible pool size is
* reported as the current size of the workers set.
*
* runState变量提供主要生命周期控制,具有以下值:
* RUNNING: 接受新的任务并且处理正在排队的任务
* SHUTDOWN:不接受新的任务,但是处理正在排队的任务
* STOP:不接受新的任务,不处理正在排队的任务,打断目前正在处理的任务
* TIDYING:所有的任务都已经终止,workerCount为零,线程转换到TIDYING状态,并且即将执行terminated()函数。
* TERMINATED: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 当调用shutdown()或finalize()函数
* On invocation of shutdown(), perhaps implicitly in finalize()
* (RUNNING or SHUTDOWN) -> STOP 当调用shutdownNow()
* On invocation of shutdownNow()
* SHUTDOWN -> TIDYING 当workers和workQueue都是空的时候
* When both queue and pool are empty
* STOP -> TIDYING 当workers是空的时候
* Whe