ExecutorService的submit與execute方法都能執(zhí)行任務窘疮,但在使用過程趣钱,發(fā)現(xiàn)其對待run方法拋出的異常處理方式不一樣。
兩者執(zhí)行任務最后都會通過Executor的execute方法來執(zhí)行裂问,但對于submit喇聊,會將runnable物件包裝成FutureTask,其run方法會捕捉被包裝的Runnable Object的run方法拋出的Throwable異常芜飘,待submit方法所返回的的Future Object調用get方法時务豺,將執(zhí)行任務時捕獲的Throwable Object包裝成java.util.concurrent.ExecutionException來拋出。
而對于execute方法嗦明,則會直接拋出異常笼沥,該異常不能被捕獲,想要在出現(xiàn)異常時做些處理,可以實現(xiàn)Thread.UncaughtExceptionHandler接口:
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
public void uncaughtException(Thread t, Throwable e) {
System.out.println(\"caught \"+e);
}
}
class HandlerThreadFactory implements ThreadFactory{
public Thread newThread(Runnable r) {
Thread t=new Thread(r);
t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
return t;
}
}
ExecutorService exec=Executors.newCachedThreadPool(new HandlerThreadFactory())