前言
相信大家都用过线程池,就是线程池先创建一堆线程,然后进行复用,这就不禁引人思考,是如何进行复用的
提示:本文只是简单剖析,并没有考虑拒绝策略
一、线程池如何使用?
很简单
/**
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
**/
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4,
60L, TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>(1024),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
二、线程的执行
1.execute执行分析
执行: threadPoolExecutor.execute(t1);
点进去看看execute怎么执行的
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);
workerCountOf( c ) < corePoolSize 判断当前启动的线程是否大于线程池的核心线程数
启动线程小于核心线程数时
addWorker(command, true)
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
...
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
...
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
这有点长,关注几个核心代码
w = new Worker(firstTask);
final Thread t = w.thread;
t.start();
Worker是什么我们稍后分析,先记住。
当前启动线程等于核心线程数时,就是不需要再新增线程时,此时需要复用
if (isRunning(c) && workQueue.offer(command))
把线程添加进队列
2.Worker是什么
复用的关键在于这个Worker
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
这个Worker也是一个Runable,那就关注他的run方法
public void run() {
runWorker(this);
}
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);
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);
}
}
看这个代码就是大循环,不断从在Tasks中获取task(Runnable),然后Start,就是一个大线程不断的调用 t1,t2,t3,t4…
我们再看看Task是啥?
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;
}
}
}
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
就是那个workQueue这个队列出队的的线程,那这个workQueue是啥?
private final BlockingQueue<Runnable> workQueue;
这就是我们自己在new ThreadPoolExecutor时候传进去的workQueue
总结
ALL in all,线程池的复用就是维护了线程池维护了一些大线程(用于执行我们execute 的Runnable),这个大线程一直循环,从workQueue取出Runnable去调用该Runnable的run()方法.
有大神发现我的不对,欢迎指正