1. 工作流程
- 判断是否核心线程
- 加入阻塞队列
- 执行拒绝策略
2. 重用线程
while (task != null || (task = getTask()) != null){
...
}
在addWorker()方法中有上述代码,该段代码的作用就是首先会判断task是否为空(也就是当前任务)。如果为空的话,会执行getTask()方法,getTask()方法的作用就是判断阻塞队列中是否还有没有执行的任务,如果有的话会用当前线程执行。下面是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;
}
}
}
该段代码的返回类型就是Runnable,或者null。 返回Runnable: 队列中有值,如果没有则会进行阻塞即执行workQueue.take(); 返回null: 大于线程最大池的参数;超时;线程池处于stop状态;线程池处于shutdown状态,同时阻塞队列为空。
3. 代码中的好味道
class ThreadPoolExecutor:
private boolean addWorker(Runnable firstTask, boolean core)
class Worker:
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
public void run() {
runWorker(this);
}
在ThreadPoolExecutor类中有一个内部静态类Worker。通过getThreadFactory().newThread(this)生成一个新的Thread实例,并将当前Worker实例传递进去。而外围的run()方法调用的是ThreadPoolExecutor类中addWorker方法,而该方法的参数就是this(即当前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 {
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);
}
}
从代码中可以看出通过Worker获取当前线程,并从中获取task,然后执行task任务。
可以看到这边写的还是比较绕的,但其实代码的结构非常好。因为从ThreadPoolExecutor类中来说,只关心Worker,因为Worker是对Runnable的封装,所以runWorker中的参数就只有Worker,而没有Runnable,然后从Worker中取出task并进行执行。所以在Worker中生成thread的时候传递的是this指针,进一步在在run()方法中执行runWorker(this)方法,并且传递的也是this指针。这样就不会破坏Worker的封装。
还有一个非常好的点就在runWorker(Worker w)中:
Runnable task = w.firstTask; w.firstTask = null;
即时的将firstTask进行置空,避免引发内存泄漏。
4. 线程池参数的设定
- IO密集型 t = N * 2;
- CPU密集型 t = N + 1;// 此处设定为+1的原因是,防止因为置页错误引发线程中断导致空出一个CPU,+1操作可以弥补这种情况带来的影响。