线程池创建以及执行任务过程分析:
1. 创建线程池
Creates a new ThreadPoolExecutor with the given initial parameters.
Params:
corePoolSize – the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize – the maximum number of threads to allow in the pool
keepAliveTime – when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
unit – the time unit for the keepAliveTime argument
workQueue – the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
threadFactory – the factory to use when the executor creates a new thread
handler – the handler to use when execution is blocked because the thread bounds and queue capacities are reached
Throws:
IllegalArgumentException – if one of the following holds: corePoolSize < 0 keepAliveTime < 0 maximumPoolSize <= 0 maximumPoolSize < corePoolSize
NullPointerException – if workQueue or threadFactory or handler is null
1. public ThreadPoolExecutor(int corePoolSize, //线程池核心线程数,不管线程是否空闲
int maximumPoolSize, //线程池最大线程数目,当workqueue满了以后,在线程池中还可以创建线程的最大数目
long keepAliveTime,//超过核心线程数的线程在线程池中能呆的最久时间
TimeUnit unit,//上述时间的单位
BlockingQueue<Runnable> workQueue,//核心线程数满了以后,新来的任务需要被放到任务队列中
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
2. 参考https://www.cnblogs.com/moonfair/p/13477974.html
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));//初始状态是Running 状态,0个工作线程,用来记录线程池状态和工作线程数量
private static final int COUNT_BITS = Integer.SIZE - 3; //将原子类的AtomicInteger的二进制位数(32位),拆分高3位(表示线程的运行状态)和低29位(表示工作线程数量)
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// 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;
// Packing and unpacking ctl
private static int runStateOf(int c) { return c & ~CAPACITY; }
private static int workerCountOf(int c) { return c & CAPACITY; }
private static int ctlOf(int rs, int wc) { return rs | wc; }
2.执行任务过程分析:
-
当有任务进来时候,先通过ctl判断当前工作线程数目是否小于核心线程数
-
如果当前线程数<corePoolSize, 排除异常情况,通过compareAndIncrementWorkerCount增加工作线程数量
-
创建worker添加到 workers,添加过程需要添加ReentrantLock的lock锁,保证加入workers的hashset期间的线程安全。添加成功以后运行worker(本质是thread)的thread
-
如果当前线程数>=corePoolSize, 在当前线程池是运行状态的前提下,将任务添加到workQueue
-
如果workQueue的队列已经满了, 在当前工作线程小于最大线程数maximumPoolSize的前提下,和上面方式一样添加worker到workers的hashset。
-
如果当前工作线程大于最大线程数maximumPoolSize,则通过RejectedExecutionHandler的处理策略来处理。
3. 当有空闲线程时候如何从workQueue里取任务?
工作线程worker的run方法中,会一直循环运行,当当前的任务运行完以后,会从workQueue当中取任务来执行。
4. 最大线程超过核心线程的线程在线程池中的存在时间如何计算?
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) ://如果timed为true说明worker有可能要被关闭,这里调用的代码含义:如果超过keepAliveTime纳秒还没取到任务,就返回null,后面会调用processWorkerExit把worker关闭
workQueue.take();//否则任务队列为空就阻塞在这里,直到任务队列再有任务
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
5. 核心线程一直存在吗?
通过参数allowCoreThreadTimeOut来设置,默认为false,表示即便核心工作线程已经空闲,也还存活。如果设置为true,通过keepAliveTime来计算超时。
原创文章,作者:745907710,如若转载,请注明出处:https://blog.ytso.com/275836.html