0
我的代碼中的第二個線程將拋出一個除以0的異常,但我只會在第一個線程完成後才能捕獲它。第一個線程可能會運行幾天,所以這意味着我只會在發生它的幾天後捕獲我的異常。 我可以解決這個問題沒有繼承ThreadPoolExecutor並覆蓋afterExecute?如何在執行多個線程時立即捕獲錯誤?
這裏是我的代碼:
ExecutorService executor = Executors.newCachedThreadPool();
Future<Integer> future = executor.submit(new MyTestC(4000));
Future<Integer> future2 = executor.submit(new MyTestC(0));
ArrayList<Future<Integer>> futures = new ArrayList<>();
futures.add(future); futures.add(future2);
for(Future<Integer> f: futures)
{
try {
int result = f.get();
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
class MyTestC implements Callable<Integer> {
int sleep;
public MyTestC(int sleep)
{
this.sleep = sleep;
}
@Override
public Integer call() throws Exception {
if(sleep > 0)
Thread.sleep(sleep);
//If 0 will throw exception:
int tmp = 4/sleep;
return sleep;
}
}
不錯,TIL關於'ExecutorCompletionService'。 +1。 – 2013-04-06 13:06:24