学习线程池过程中产生的问题
- 线程池的提交过程是怎么样的
- 线程池是如何复用的
- Runnable 和 Callable 提交有什么区别
- 如何辨别外围线程和非核心线程
- 存活工夫达到时如何敞开线程
线程池的提交
线程池的提交有 3 种形式:
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
能够看到别离是 2 个 Runnable 和 1 个 Callable 的提交,那为什么有两个 Runnable 的提交呢。通常咱们都是认为 Runnable 和 Callable 的区别是 Callable 是能够返回一个后果。其实 Runnable 也是能够返回后果的,依据参数 T result 能够看出 T result 就是返回后果,如果不传,那么默认返回 NULL。
接下来进入 submit 办法
public <T> Future<T> submit(Callable<T> task) {if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
public <T> Future<T> submit(Runnable task, T result) {if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
public Future<?> submit(Runnable task) {if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
这三个办法是先调用 newTaskFor 失去一个 RunnableFuture,再提交执行。
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {return new FutureTask<T>(runnable, value);
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {return new FutureTask<T>(callable);
}
newTaskFor 内结构的 FutureTask 就是咱们用来获取执行状态和后果的适配类了。在 FutureTask 类内,则是对立适配为 Callable,只不过 Runnable 返回 NULL 或传入的固定值。
咱们再看看 ThreadPoolExecutor 的执行过程:
public void execute(Runnable command) {if (command == null)
throw new NullPointerException();
//1、判断是否在外围线程内,如果是则尝试创立外围线程
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {if (addWorker(command, true))
return;
c = ctl.get();}
//2、超出外围线程数则尝试间接退出队列
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);
}
//3、退出队列失败则尝试创立非核心线程,留神第二个参数,在增加工作前要做检测
//,ture 示意检测小于外围线程数,false 示意检测小于最大线程数
else if (!addWorker(command, false))
//4、执行回绝策略
reject(command);
}
很显著,在提交工作的过程中,最重要的就是 addWorker 这个办法。
private boolean addWorker(Runnable firstTask, boolean core) {
//1、做各种检测,并且尝试 CAS 线程数,胜利则持续,失败则重试或返回
retry:
for (;;) {int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
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 {
//2、新建 Worker 来治理工作的执行,并将 Worker 增加到 workers 中治理
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 rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {mainLock.unlock();
}
if (workerAdded) {
//3、终于到执行这一步,间接运行 start 执行
t.start();
workerStarted = true;
}
}
} finally {if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
后面说到,参数 boolean core 管制增加外围 / 非核心线程,然而在该办法中只有判断时用到了 core,所以如何辨别外围 / 非核心线程呢?答案是不辨别,这两兄弟在线程池看起来没有区别,只须要思考线程数和外围数,最大数就能够。
间接运行 start,那么队列里的工作怎么办呢?这在 Worker 外部解决。Worker 是一个实现了 Runnable 的外部类,它的执行逻辑全副在 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 {
//1、循环获取工作,直到没有工作
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 {
//2、前置解决,默认空实现
beforeExecute(wt, task);
Throwable thrown = null;
try {
//3、间接执行 run,这样就能够保障不同的逻辑在同一个线程内执行
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 {
//4、后置解决,默认空实现
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();}
}
completedAbruptly = false;
} finally {
5、移除 Worker
processWorkerExit(w, completedAbruptly);
}
}
咱们能够猜到,getTask 就是从队列内获取工作,当获取不到工作,退出循环后,就移除 worker。
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 {
// 如果须要判断超时,那么就在 keepAliveTime 工夫后拉取工作,否则就阻塞拉取工作
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {timedOut = false;}
}
}
参数 timed 代表是否须要判断超时,timedOut 代表是否超时。如果以后线程数在外围线程数内并且外围线程容许超时,那么 timed 就是 false,这种状况下只有空队列阻塞和获取到工作返回两种状况;而如果是以后线程数超过外围线程,那么也有两种状况,队列有工作间接获取,队列没有工作在 keepAliveTime 后再获取一次工作,没有工作就完结执行。