一、常见线程池:
1. 固定线程数量的线程池
i. 通过Executors.newFixedThreadPool 来创建
ii. 核心线程数和最大线程数一样
iii. 达到核心线程数后,空闲线程不会超时被终止或释放。
iiii. 每添加一个任务后,会将任务添加到工作任务列队列,线程池创建一个线程,线程数等于核心线程数时,就不会再创建线程。
2. 单线程的线程池
i 通过 Executors.newSingelThreadExecutor 来创建。
ii. 核心线程数和最大线程数一样,且均为 1 ,也就是只有一个线程在执行队列的工作任务。
iii. 使用了代理模式来创建线程池。
3. 可缓存的线程池
i 通过 Executors.newCachedThreadPool 来创建
ii. 核心线程数为 0 ,最大线程数为无限大(实际是 int 最大值),空闲线程可以缓存 60s,空闲超过60s的线程会被回收。
iii. 使用了 SynchronousQueue 同步队列,添加任务的同时,需有工作线程来取任务才可完成任务的添加和执行。
4. 定时执行的线程池
i. 通过 Executors.newScheduledThreadPool 来创建
ii. 可指定核心线程数,最大线程数为无限大(实际是 int 最大值),核心线程数空闲不会超过被回收。
iii. 使用了 DelayedWorkQueue 延时队列,通过延时队列来控制时间来执行
二、 线程执行源码解释:
/**
* Executes the given task sometime in the future. The task
* may execute in a new thread or in an existing pooled thread.
*
* If the task cannot be submitted for execution, either because this
* executor has been shutdown or because its capacity has been reached,
* the task is handled by the current {@code RejectedExecutionHandler}.
*
* @param command the task to execute
* @throws RejectedExecutionException at discretion of
* {@code RejectedExecutionHandler}, if the task
* cannot be accepted for execution
* @throws NullPointerException if {@code command} is null
*/
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* 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.
*/
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
execute 底层执行过程:
1. 检查线程池的运行状态和工作线程数量,如果工作线程数 < 核心线程数,则会创建一个新的线程来执行给定任务(调用addWorker来执行任务)
2. 如果超过了核心线程数,把任务放到工作队列中,若工作队列没有满,则添加任务后,仍检查一下线程池状态,如果没有继续运行(不是RUNNING状态)就把任务移除,使用拒绝策略来处理当前任务;否则将创建或唤醒工作线程来执行任务
3. 线程池非RUNNING状态或添加任务失败后,使用拒绝策略来处理当前任务
addWorker 源码分析:
/**
* Checks if a new worker can be added with respect to current
* pool state and the given bound (either core or maximum). If so,
* the worker count is adjusted accordingly, and, if possible, a
* new worker is created and started, running firstTask as its
* first task. This method returns false if the pool is stopped or
* eligible to shut down. It also returns false if the thread
* factory fails to create a thread when asked. If the thread
* creation fails, either due to the thread factory returning
* null, or due to an exception (typically OutOfMemoryError in
* Thread.start()), we roll back cleanly.
*
* @param firstTask the task the new thread should run first (or
* null if none). Workers are created with an initial first task
* (in method execute()) to bypass queuing when there are fewer
* than corePoolSize threads (in which case we always start one),
* or when the queue is full (in which case we must bypass queue).
* Initially idle threads are usually created via
* prestartCoreThread or to replace other dying workers.
*
* @param core if true use corePoolSize as bound, else
* maximumPoolSize. (A boolean indicator is used here rather than a
* value to ensure reads of fresh values after checking other pool
* state).
* @return true if successful
*/
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
// 1. 检查状态
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
// 检查工作队列
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize)) // 是否超过核心线程数/最大线程数
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
// 创建 worker(AQS)
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}