在阿里巴巴Java开发手册中有这么两段话,以下图所示java
能够看到提到的两点,第一要求不能显示的建立线程,也就是new Thread的这种形式,须要使用线程池对线程进行管理,第二不容许使用官方提供的四种线程池,而是须要经过自行建立的方式去建立线程池,更加理解线程池的容许规则安全
本文就基于JDK1.8的代码,对线程池源码进行解析,带你们可以更好的理解线程池的概念以及其运行规则,若有错误,请你们指出多线程
先从构造函数看起:函数
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) 复制代码
有的朋友可能还不是很清晰,举个例子,一个公司,核心线程就是表明公司的内部核心员工,最大线程数量就是员工的最大数量,可能包含非内部员工,由于有一些试点或者简单的项目,须要一些外协人员来作,也就是非核心线程,那么当这些项目作完了或者失败了,公司为了节约用人成本,就遣散非核心员工,也就是闲置线程的存活时间。假如核心员工每一个人都很忙,可是需求又一波接一波,那就职务排期,也就是任务队列,当任务队列都满了时候,还要来需求?对不起,不接受,直接拒绝,这也就是handler对应的拒绝策略了,能够例子不是很合适,可是主要帮助你们理解下大概的意思。oop
打开源码类,能够看到以下几个变量学习
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
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; }
复制代码
AtomicInteger是一个原子操做类,保证线程安全,采用低29位表示线程的最大数量,高3位表示5种线程池状态,维护两个参数,workCount和runState。workCount表示有效的线程数量,runState表示线程池的运行状态。ui
terminated()
方法已经执行完成引用一张图片帮助你们理解5个状态this
execute()atom
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();
//若是当前线程数量小于核心线程数量,执行addWorker建立新线程执行command任务
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
//若是当前是运行状态,将任务放入阻塞队列,double-check线程池状态
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
//若是再次check,发现线程池状态不是运行状态了,移除刚才添加进来的任务,而且拒绝改任务
if (! isRunning(recheck) && remove(command))
reject(command);
//处于运行状态,可是没有线程,建立线程
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
//往线程池中建立新的线程失败,则reject任务
else if (!addWorker(command, false))
reject(command);
}
复制代码
这里大概总结下execute方法的执行流程,其实你们看源码方法注释是同样很好的学习方法spa
这里注意一点,当核心线程满的时候,并不会去直接建立非核心线程去执行任务,而是先放进任务队列,能够理解为需求任务首先是须要让内部核心员工去完成的,任务队列的优先级是高于非核心员工的,addWorker(),这里的传进去的boolean值,就表明着建立核心线程或者非核心线程
reject()
final void reject(Runnable command) {
handler.rejectedExecution(command, this);
}
复制代码
拒绝任务很简单,reject方法会调用handler的rejectedExecution(command,this)方法,handler是RejectedExecutionHandler接口,默认实现是AbortPolicy,下面是AbortPolicy的实现:
public static class AbortPolicy implements RejectedExecutionHandler {
public AbortPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
复制代码
能够看到默认策略是直接抛出异常的,这只是默认使用的策略,能够经过实现接口实现本身的逻辑。
addWorker()
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// 这里return false的状况有如下几种
//1.当前状态是stop及以上 2.当前是SHUTDOWN状态,可是firstTask不为空
//3.当前是SHUTDOWN状态,可是队列中为空
//从第一节咱们知道,SHUTDOWN状态是不执行进来的任务的,可是会继续执行队列中的任务
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 {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
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;
}
复制代码
这里就主要流程分析下
Worker()
private final class Worker extends AbstractQueuedSynchronizer implements Runnable {
/** 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;
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
public void run() {
runWorker(this);
}
......
}
复制代码
能够看到,Worker内部维护,一个线程变量以及任务变量,启动一个 Worker对象中包含的线程 thread, 就至关于要执行 runWorker()方法, 并将该 Worker对象做为该方法的参数.
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 {
//task不为空,执行当前任务,任务执行完后将task置位空,getTask方法接着不断从队列中取任务
while (task != null || (task = getTask()) != null) {
w.lock();
//再次check线程池状态,若是是stop状态,直接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);
}
}
复制代码
经过while循环不断的调用getTask方法,获取任务task并进行执行,若是任务都执行完,跳出循环,线程结束并减小当前线程数量。
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;
}
}
}
复制代码
这里主要有两个判断须要说明下:
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize
allowCoreThreadTimeOut :这个第一节有说过,若是核心线程设置了该属性,也是须要进行回收的,wc > corePoolSize:当前线程是非核心线程也是须要回收的,知足任何一个条件,timed 置位true
timed ?workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :workQueue.take()
若是上述的timed标志位为true,调用poll方法获取任务,同时设置超时时间,若是没有任务,则超时返回null,跳出runWorker的循环,线程结束被回收,若是为false,调用take方法,此时若是没有任务,不会返回null,而是会进入阻塞状态,等待任务,不会被回收
线程池中的细节比较多,大体作一下总结概括
大概分析就是这么多,但愿有可以帮助到一些朋友更好的理解线程池的工做原理以及在使用中可以更好的使用,若有疑问或者错误,欢迎一块儿讨论