线程池的提交方式有submit和execute
execute没有返回值,并且会打印异常信息
submit返回的是一个future ,默认情况不会打印异常信息,但可以通过这个future取到线程执行的结果或者异常信息:
// submit
Future<String> future = executorService.submit(() -> testService.dosth());
try {
future.get();
} catch (Exception e) {
log.error("submit 线程异常 ", e);
}
或者使用try-catch
// submit
executorService.submit(() -> {
try {
testService.dosth();
} catch (Exception e) {
log.error("submit 线程异常 ", e);
}
});
submit源码在底层还是调用的execute方法,只不过多一层future封装,future里面的run方法try-catch了所有的异常,通过setException(ex)方法设置到了变量outcome里面, 可以通过future.get获取到outcome
解决办法
重写afterExecute方法一