线程池任务分配机制三阶段流程
原文
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
译文
- 核心线程创建阶段
当活跃线程数 < 核心线程数(corePoolSize)时:- 尝试以原子操作启动新工作线程
- 新线程将指定任务作为首任务执行
- 通过addWorker方法的原子校验机制,同时检测:
▸ 线程池运行状态(runState)
▸ 当前工作线程数(workerCount) - 防止因状态突变导致虚假线程创建(如检查期间线程池意外关闭)
- 任务队列缓冲阶段
当任务成功入队后:- 需进行二次状态验证:
▶ 校验是否存在线程意外终止(检查后消亡)
▶ 确认线程池未在此方法执行期间关闭 - 根据验证结果执行:
▶ 若线程池已停止:执行任务回滚操作
▶ 若无存活线程:启动新线程处理队列
- 需进行二次状态验证:
- 饱和处理阶段
当任务队列已满时:- 尝试创建非核心线程扩展处理能力
- 若线程创建失败,表明:
▶ 线程池已执行shutdown()
▶ 或已达最大线程数(maximumPoolSize) - 最终执行任务拒绝策略
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 程序员小航
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果