2013-04-06 74 views
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; 
} 

}

回答

2

您可以使用ExecutorCompletionService来解决这个问题。它将按照它们完成的顺序返回期货。

+0

不错,TIL关于'ExecutorCompletionService'。 +1。 – 2013-04-06 13:06:24