ThreadPoolExecutor源码分析
2018-03-13 本文已影响0人
倦飞知还
前言
线程池能够对线程进行管理和复用,并且还能够克服线程数量的限制。如果频繁的使用线程,使用线程池显然比使用线程更加的高效。本文介绍了线程池的使用,并且对线程池的源码进行了剖析。
线程池的使用
构造方法
线程池的构造方法最后都会调用下面的构造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
- corePoolSize :表示的是线程池中一直存活着的线程的最小数量, 这些一直存活着的线程又被称为核心线程. 默认情况下, 核心线程的这个最小数量都是正数, 除非调用了allowCoreThreadTimeOut()方法并传递参数为true, 设置允许核心线程因超时而停止(terminated), 在那种情况下, 一旦所有的核心线程都先后因超时而停止了, 将使得线程池中的核心线程数量最终变为0。
- maximumPoolSize:maximumPoolSize 表示线程池内能够容纳线程数量的最大值. 当然, 线程数量的最大值还不能超过常量 CAPACITY (1 << 29 - 1)的数值大小。
- keepAliveTime以及unit:非核心线程的最大阻塞时间。如果非核心线程超过这个时间未执行任务,则会取消自旋,停止工作。
- workQueue:任务的暂存队列。当核心线程数已满之后,任务会先添加到暂存队列中。
- threadFactory:线程工厂, 用于创建线程. 如果我们在创建线程池的时候未指定该 threadFactory 参数, 线程池则会使用 Executors.defaultThreadFactory() 方法创建默认的线程工厂.
- handler :处理当线程池已达到最大值并且暂存队列已满的情况下或者线程池被关闭情况下的异常。
创建线程
可以直接创建线程
new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>())
可以通过Executors进行创建
- Executors.newCachedThreadPool
- Executors.newFixedThreadPool
- Executors.newWorkStealingPool
- Executors.newSingleThreadExecutor
- Executors.newScheduledThreadPool
提交任务
ExecutorService executorService = ...
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("OK, thread name: " + Thread.currentThread().getName());
}
});
关闭线程
-
shutdown :自旋的方式关闭空闲线程。
-
shutdownNow:自旋的方式关闭空闲线程,并且清空等待队列中的任务。
源码分析
整体架构
ThreadPoolExecutor主要成员变量
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private final BlockingQueue<Runnable> workQueue;
private final ReentrantLock mainLock = new ReentrantLock();
private final HashSet<Worker> workers = new HashSet<Worker>();
private final Condition termination = mainLock.newCondition();
- ctl 状态位,前29位表示线程的数量,后3位表示线程的状态,包括:
// 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;
- workQueue 工作队列,用于暂存任务
- mainLock和condition,用于线程同步
- workers 用于保存线程
整体流程图:
executors.jpg- 调度: 决定线程如何取队列中的任务。
- 线程队列: 存放并管理着一系列线程, 这些线程都处于阻塞状态或休眠状态
- 任务队列: 存放着用户提交的需要被执行的任务. 一般任务的执行 FIFO 的, 即先提交的任务先被执行
任务添加过程
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
//1
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
//2
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);
}
//3
else if (!addWorker(command, false))
reject(command);
}
- 模块一:先判断当前核心线程数量是否已到达指定数量,如果未达到,则增加核心线程,并将添加的任务作为线程的首任务。
- 模块二:如果核心线程已满,则将任务添加到任务队列,添加后还要判断添加后线程池的状态,如果线程池在添加后已经关闭,则进行关闭操作。如果没有线程了,则增开一个线程。
- 模块三:如果添加到任务失败,则增加非核心线程,并将任务作为非核心线程的首任务。
增加线程的过程
private boolean addWorker(Runnable firstTask, boolean core) {
//1
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
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
}
}
//2
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
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;
}
- 检查是否能够添加过程
- 添加并且执行线程
任务调度过程
执行线程:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
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);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
执行过程为不断尝试从队列中取出任务执行,如果本次取出的任务和上次取出的任务为空,则取消线程。
取出任务的过程是线程调度的关键:
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;
}
}
}
核心线程使用take方法,其一直挂起直到获取任务位置,非核心线程使用BlockingQueue.poll(long,TimeUnit)方法,其挂起的时间是有限制的,为keepAliveTime。