提交给ThreadPoolExecutors的任务(callable或Runnable)将转换为FuturnTask,其中包含名为callable的道具,它等于您提交的任务。 FuturnTask具有其自己的run方法,如下所示。 将捕获c.call()中抛出的所有异常或可投掷,并将其放入名为outcome的道具中。调用FuturnTask的get方法时,将抛出outcome
来自Jdk1.8的FuturnTask.run源代码
public void run() {
...
try {
Callable 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
}
}