一.ThreadPoolExecutor简介
1.ThreadPoolExecutor的继承关系如下图:
2.ThreadPoolExecutor里面的属性和方法,还有内部类:
二.分析ThreadPoolExecutor执行流程及原理
1.首先我们来分析的他的构造函数:
Executor executor = new ThreadPoolExecutor(10, 10, 1000L, TimeUnit.SECONDS, arrayBlockingQueue);
这里是创建了一个线程池,他具体的构造函数源码如下:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
接着我们分析他的一个个的入参:
corePoolSize:核心的线程的数量
maximumPoolSize:线程池里面最大线程的数量
keepAliveTime:空闲的线程的生存时间
unit:时间单位
workQueue:任务队列,又不同的实现包括有:
(①:ArrayBlockingQueue:数组阻塞队列,他是提个有界的数组,遵循着FIFO先进先出的原则、
②:LinkedBlockingQueue:链表阻塞队列,他也遵循着先进先出的原则、
③:SynchronousQueue:不存储任何一个元素的,在把一个元素put进队列之前,必须要有一个线程进行take取走的操作,否则会一直阻塞)
ThreadFactory:线程工厂,创建线程,设置优先级等等
RejectedExecutionHandler:拒绝任务的策略
2.接着我们来看他的execute()方法:
execute方法是任务进入到线程池的第一步,他的源码如下:
public void execute(Runnable command) {
//1.判断任务是否为空
if (command == null)
throw new NullPointerException();
int c = ctl.get();
//2.比较当前的线程的数量和设置的核心的线程数量大小
if (workerCountOf(c) < corePoolSize) {
//3.如果当前的线程的数量小于设置的核心的线程数量,则将任务addWorker
if (addWorker(command, true))
return;
c = ctl.get();
}
//4.使用isRunning方法来判断线程池的状态,任务加入到任务队列
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);
}
他的具体流程如下图:
3.接下来我们分析addWorker方法:
他的源码如下:
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);
//2.判断当前的线程数量和corePoolSize,maximumPoolSize的大小关系
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,线程池里面的线程
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;
}
简单的分析:addWorker方法首先在线程池状态为运行状态和当前的线程数量没有达到核心的线程的数量的状态的时候,利用CAS将线程池的数量进行加一的操作,然后又通过ReetrantLock来确保线程池是运行状态的,然后把新创建的worker添加workers集合里面去。
4.接着我们来分析一下什么是Worker
查看Worker的源码如下:
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
//1.Worker继承了AbstractQueuedSynchronizer,也实现了Runnable接口
/**
* This class will never be serialized, but we provide a
* serialVersionUID to suppress a javac warning.
*/
private static final long serialVersionUID = 6138294804551838833L;
/** Thread this worker is running in. Null if factory fails. */
final Thread thread;
/** Initial task to run. Possibly null. */
Runnable firstTask;
/** Per-thread task counter */
volatile long completedTasks;
/**
* Creates with given first task and thread from ThreadFactory.
* @param firstTask the first task (null if none)
*/
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(this);
}
// Lock methods
//
// The value 0 represents the unlocked state.
// The value 1 represents the locked state.
protected boolean isHeldExclusively() {
return getState() != 0;
}
protected boolean tryAcquire(int unused) {
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
protected boolean tryRelease(int unused) {
setExclusiveOwnerThread(null);
setState(0);
return true;
}
public void lock() { acquire(1); }
public boolean tryLock() { return tryAcquire(1); }
public void unlock() { release(1); }
public boolean isLocked() { return isHeldExclusively(); }
void interruptIfStarted() {
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}
}
可以这样理解worker,在创建worker的时候,已经将任务firstTask
传进去,并且创建了线程,相当于一个worker里面已将有了Runable和Thread,同时他又实现了Runable接口,他又可以作为任务被执行。
5.接着我们看看runWorker方法:
源码如下:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//1.会不断的循环去获取线程
while (task != null || (task = getTask()) != null) {
//2.获取锁资源,避免中断
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);
}
}
分析:传入一个worker,这个worker会执行第一个任务,或者不断的去获取任务表里面的任务去执行。
6.getTask方法分析:
源码如下:
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;
}
}
}
getTask方法会用一个循环来不断的获取任务,然后根据超时配置来判断使用
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS)来获取任务,还是 workQueue.take()来获取任务。
BlockingQueue.poll 阻塞指定的时间尝试获取任务,如果超过指定的时间还未获取到任务就返回null。
BlockingQueue.take 这种方法会在取到任务前一直阻塞。