线程池实现“线程复用”的原理
ThreadPoolExecutor
/**
* int corePoolSize 核心线程数
* int maximumPoolSize 线程池最大容量
* long 线程空闲时间,线程存活时间
* TimeUnit 时间单位
* threadFactory 线程工厂
* handler 执行拒绝策略对象
*/
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return null;
}
}, new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
}
});
execute 方法
public void execute(Runnable command) {
//首先会判断任务是否为空
if (command == null)
throw new NullPointerException();
int c = ctl.get();
/**
* workerCountOf 当前使用的线程数
* corePoolSize 核心线程数
* workerCountOf < corePoolSize 那么加开线程
*/
if (workerCountOf(c) < corePoolSize) {
//添加核心线程
if (addWorker(command, true))
return;
c = ctl.get();
}
/*
* 当前线程数大于或等于核心线程
* isRunning 判断线程池是否运行状态
* 是运行状态那么把任务添加到队列中
*/
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
//线程停止运行 删除任务 并执行拒绝策略
if (! isRunning(recheck) && remove(command))
reject(command);
//线程池在运行但是线程数为0 的时候需要添加新的线程
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
/**
* 线程池不是running的状态
* 线程数大于或等于核心线程数
* 任务队列已经满了
* 添加一个新的线程达到最大线程数为止
* 达到最大线程数开始执行拒绝策略
**/
else if (!addWorker(command, false))
reject(command);
}
addWorker 方法
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (int c = ctl.get();;) {
// Check if queue empty only if necessary.
if (runStateAtLeast(c, SHUTDOWN)
&& (runStateAtLeast(c, STOP)
|| firstTask != null
|| workQueue.isEmpty()))
return false;
for (;;) {
if (workerCountOf(c)
>= ((core ? corePoolSize : maximumPoolSize) & COUNT_MASK))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateAtLeast(c, SHUTDOWN))
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 {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int c = ctl.get();
if (isRunning(c) ||
(runStateLessThan(c, STOP) && firstTask == null)) {
if (t.getState() != Thread.State.NEW)
throw new IllegalThreadStateException();
workers.add(w);
workerAdded = true;
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
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 {
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);
try {
task.run();
afterExecute(task, null);
} catch (Throwable ex) {
afterExecute(task, ex);
throw ex;
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}