ThreadPoolExecutor
https://www.cnblogs.com/vipstone/p/9984238.html
线程池状态:
public class ThreadPoolExecutor extends AbstractExecutorService { ... * 线程池状态: * 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; * * RUNNING:这个没什么好说的,这是最正常的状态:接受新的任务,处理等待队列中的任务; * SHUTDOWN:不接受新的任务提交,但是会继续处理等待队列中的任务; * STOP:不接受新的任务提交,不再处理等待队列中的任务,中断正在执行任务的线程; * TIDYING:所有的任务都销毁了,workCount 为 0。线程池的状态在转换为 TIDYING 状态时,会执行钩子方法 terminated(); * TERMINATED:terminated() 方法结束后,线程池的状态就会变成这个; * RUNNING 定义为 -1,SHUTDOWN 定义为 0,其他的都比 0 大,所以等于 0 的时候不能提交任务,大于 0 的话,连正在执行的任务也需要中断。 * * 各个状态的转换过程有以下几种: * * RUNNING -> SHUTDOWN:当调用了 shutdown() 后,会发生这个状态转换,这也是最重要的; * (RUNNING or SHUTDOWN) -> STOP:当调用 shutdownNow() 后,会发生这个状态转换,这下要清楚 shutDown() 和 shutDownNow() 的区别了; * SHUTDOWN -> TIDYING:当任务队列和线程池都清空后,会由 SHUTDOWN 转换为 TIDYING; * STOP -> TIDYING:当任务队列清空后,发生这个转换; * TIDYING -> TERMINATED:这个前面说了,当 terminated() 方法结束后; * // 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; ... }
/** * Performs blocking or timed wait for a task, depending on * current configuration settings, or returns null if this worker * must exit because of any of: * 1. There are more than maximumPoolSize workers (due to * a call to setMaximumPoolSize). * 2. The pool is stopped. * 3. The pool is shutdown and the queue is empty. * 4. This worker timed out waiting for a task, and timed-out * workers are subject to termination (that is, * {@code allowCoreThreadTimeOut || workerCount > corePoolSize}) * both before and after the timed wait, and if the queue is * non-empty, this worker is not the last thread in the pool. * * @return task, or null if the worker must exit, in which case * workerCount is decremented */ private Runnable getTask() { boolean timedOut = false; // Did the last poll() time out? for (;;) { int c = ctl.get(); int rs = runStateOf(c); // Check if queue empty only if necessary. if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) { decrementWorkerCount(); return null; } int wc = workerCountOf(c); // Are workers subject to culling? boolean timed = allowCoreThreadTimeOut || wc > corePoolSize; if ((wc > maximumPoolSize || (timed && timedOut)) && (wc > 1 || workQueue.isEmpty())) { if (compareAndDecrementWorkerCount(c)) return null; continue; } try { Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take(); if (r != null) return r; timedOut = true; } catch (InterruptedException retry) { timedOut = false; } } }
posted on 2019-09-09 16:32 GhostSugar 阅读(184) 评论(0) 编辑 收藏 举报