任务先放到核心线程池,放不下了再放到阻塞队列,还是放不下就放到最大线程池中.
Screen Shot 2022-04-30 at 9.42.53 PM.png重点关注,阻塞队列,回收时间实现,拒绝策略,ThreadFactory自定义线程池这些参数.
Screen Shot 2022-04-30 at 9.45.37 PM.png- 存储线程状态:
// runState is stored in the high-order bits
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = 0 << COUNT_BITS;
private static final int STOP = 1 << COUNT_BITS;
private static final int TIDYING = 2 << COUNT_BITS;
private static final int TERMINATED = 3 << COUNT_BITS;
- 执行任务判断的依据state
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Screen Shot 2022-04-30 at 9.49.26 PM.png
- 抛出异常 适合业务容错低的场景
- 直接丢失,比如做分析,日志这些场景
- 最老移除
- 谁调用execute谁去执行这个任务
重新认识了阻塞队列后再去看线程池的设计感触就会更多了.
优先级队列用二叉树去排序.
- 循环的从阻塞队列中获取任务.
task不为空 或者阻塞队列中拿到了任务
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
-
唤醒线程的几种方式
notify ,notifyall,unpark,conditional.signal -
DelayQueue实现
DelayQueue内部封装了一个PriorityQueue,它会根据time的先后时间排序
网友评论