當(dāng)我們通過(guò)submit提交任務(wù)到線(xiàn)程池,如果線(xiàn)程失敗,我們?cè)趺慈ゲ东@這個(gè)失敗而拋出來(lái)的異常呢
方法1:通過(guò)調(diào)用返回對(duì)象 FutureTask的get方法**
FutureTask.get() will re-throw any exception thrown by the task as an ExecutorException
缺點(diǎn):該方法是阻塞調(diào)用,會(huì)阻塞提交任務(wù)的線(xiàn)程
方法2:在提交的線(xiàn)程任務(wù)的 run() or call()使用 try{}catch{}Exceptoion{}進(jìn)行處理
Executors.newCachedThreadPool().submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
try {
int a = 1 / 0;
return 1;
} catch (Exception e) {
e.printStackTrace();
} finally {
//you can do something here,e.g. log execution
}
return 0;
}
});
方法3:改寫(xiě)ThreadPoolExecutor的afterExecute方法
方法示例來(lái)自jdk的ThreadPoolExecutor的afterExecute方法注釋
class ExtendedExecutor extends ThreadPoolExecutor {
// ...
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
Object result = ((Future<?>) r).get();
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
if (t != null)
System.out.println(t);
}
}
參考資料:https://stackoverflow.com/questions/2554549/handling-exceptions-for-threadpoolexecutor