线程池源码解析
今天看了看线程池源码,就线程池处理流程记录下自己的理解
线程池的优点
众所周知,线程的创建是有开销的,频繁的创建销毁线程一定时浪费性能的,那么我们就有了保留旧线程的想法。
线程池的运行原理
线程池主要由两部分组成
- 线程:或者说重复利用的线程
- 队列
线程消费队列就是处理请求的过程
- 对应源码看运行原理
源代码中的注释就是线程池的运行原理
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();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
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);
}
请求进入时分几种情况
- 线程数小于核心线程数,创建核心线程
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
- 线程数大于核心线程,队列未满时,将请求加入队列
if (isRunning(c) && workQueue.offer(command))
- 队列已满时,未达到最大线程数,创建最大线程
else if (!addWorker(command, false))
- 都不行的话,就执行拒绝策略
reject(command);
一个worker就是一个线程
线程池的复用原理
- 线程的run方法会调用runWorker方法,runWorker就是一个while循环,不停的从队列中获取请求并执行,值得一提的是,触发创建线程的请求是第一个执行的,并没有添加到队列尾部
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(this);
}
// runWorker 方法已简化
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
try {
while (task != null || (task = getTask()) != null) {
task.run();
}
} finally {
processWorkerExit(w, completedAbruptly);
}
}
- 线程是如何超时销毁的
当线程没有处理的任务时,会超时销毁
获取任务代码
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
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;
}
}
}
获取不到时,该方法会返回null,线程就可以结束了
万事看到代码实现才是真正理解呀