提交的任务(Callable
或)将转换为 a ,包含一个名为等于您提交的任务的道具。FuturnTask 有自己的方法如下。所有抛出的异常或可抛出对象都将被捕获并放入名为. 调用 FuturnTask 的方法时,会抛出Runnable
ThreadPoolExecutors
FuturnTask
callable
run
c.call()
outcome
get
outcome
FuturnTask.run 来自 Jdk1.8 源码
public void run() {
...
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
// save ex into `outcome` prop
setException(ex);
}
if (ran)
set(result);
}
}
...
}
如果你想捕捉异常:
1. 斯卡夫曼的回答
2. 新建 ThreadPoolExecutor 时覆盖 `afterExecute`
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
Throwable cause = null;
if (t == null && r instanceof Future) {
try {
((Future<?>) r).get();
} catch (InterruptedException | ExecutionException e) {
cause = e;
}
} else if (t != null) {
cause = t;
}
if (cause != null) {
// log error
}
}