前言
这是笔者学习的笔记,分享出来,仅供大家参考
源码基于jdk1.8
四种线程池
并发三大特性:原子性、可见性、有序性
java保证原子性的类AtomicInteger
corePoolSize 线程池基本大小 阻塞队列满了的话 才会在corePoolSize < maximumPoolSize 下创建新的线程, 如果队列是无穷大的 那么maximumPoolSize永远也用不上,
也就是说优先corePoolSize > 阻塞队列 > maximumPoolSize, 当阻塞队列+corePoolSize不够用时,新加任务就会去创建新的线程,新建线程不能超过maximumPoolSize,maximumPoolSize-corePoolSize就是借用的,如果这部分空闲了,就要根据空闲时间来销毁线程或复用
那么执行线程也需要存储的 HashSet 阻塞队列用的BlockingQueue
1、Executors.newSigleThreadExecutor()
实例化 ThreadPoolExecutor 核心线程数 1, 最大线程数 1 空闲维持时间 0,阻塞队列 LinkedBlockingQueue
2、Executors.newFixedThreadPool(nThreads)
实例化 ThreadPoolExecutor 指定线程数量== 核心线程数 ==最大线程数, 空闲维持时间 0,阻塞队列 LinkedBlockingQueue
3、Executors.newCachedThreadPool()
实例化 ThreadPoolExecutor 核心线程数 0,最大线程数 Integer.MAX_VALUE, 空闲维持时间 60秒,阻塞队列 SynchronousQueue()
4、Executors.newScheduledThreadPool(corePoolSize)
实例化 ScheduledThreadPoolExecutor(corePoolSize) 指定核心线程数,最大线程数 Integer.MAX_VALUE,空闲维持时间 (java 0, android.jar中的改为10毫秒),阻塞队列 DelayedWorkQueue()
自定义线程池 可以直接newThreadPoolExecutor 指定线程数量 核心数 空闲维持时间 阻塞队列
线程池几种状态
- RUNNING: 接受新任务和处理队列的任务
- SHUTDOWN: 不接受新任务,但是处理队列的任务
- STOP: 不接受新任务,但是处理队列的任务,终止进行中的任务
- TIDYING: 所有任务都已终止,workerCount为零,转换为状态TIDYING的线程将运行terminated() hook method
- TERMINATED: terminated() 已执行完成
笔者总结的流程图
从execute->addWorker->runWorker
线程池类继承关系:
线程池提交任务
addWorker到线程启动再到线程复用、线程销毁
execute执行任务
/**
* 执行任务
*
* @param command 任务
*/
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
//工作线程数小于核心线程数,直接创建核心线程
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
//如果线程池RUNNING 添加到阻塞队列,
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
//如果没有RUNNING 将任务从队列中移除,移除成功执行拒绝策略
if (! isRunning(recheck) && remove(command))
reject(command);
//RUNNING或者移除失败,判断工作线程==0,创建一个非核心线程
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
//线程池没有挂了或者添加队列失败也就是队列满了,就会去创建非核心线程
//创建失败执行拒绝策略
else if (!addWorker(command, false))
reject(command);
}
/**
* 添加Worker
*
* @param firstTask 任务Runnable
* @param core true 核心, false 非核心
* @return true Worker添加成功并启动成功,false失败
*/
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
// 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 {
//实例化Worker
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
//HashSet操作 锁住先
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
//线程池状态RUNNING或者SHUTDOWN并且进来的任务是null的 执行添加任务 SHUTDOWN是可以接收新任务的
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
//如果worker的thread已经启动了抛出异常
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
//workers是HashSet,把worker加入到HashSet
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
//worker已经添加启动线程
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
可以看到addWorker里面实例化了一个Worker对象,这里很有意思,我们跟进去Worker构造函数瞧瞧
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable {
...
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
...
}
获取线程工厂创建一个thread,把Worker本身传进去了,所以addWorker()里面调用Worker.thread.start()方法会执行到Worker.run()
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable {
...
public void run() {
runWorker(this);
}
...
}
Worker run()方法执行的是runWorker(Worker)
接下来看看runWorker方法
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==null的时候getTask队列取任务
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);
// 必要时检查队列为 SHUTDOWN && isEmpty 或者 >=STOP
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
//减少工作线程数量
decrementWorkerCount();
//并终止while循环销毁线程
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())) {
//尝试减少工作线程数量1
if (compareAndDecrementWorkerCount(c))
//返回null结束while也就销毁了线程
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
//poll 队列为空返回null timed==true 工作线程>核心 所以等待keepAliveTime 后再销毁
//take 队列为空阻塞 timed==false 工作线程<=核心 不需要超时等待 阻塞直到拿到任务,所以线程也是阻塞状态
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
总结
开发路漫长,多看看源码