我的代码中的第二个线程将抛出除以 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;
}
}