我读了很多关于ExecutorService
的帖子,但我无法找到我需要的方式。立即关闭ExecutionException
我需要一些并发线程。当他们中的任何一个抛出自定义异常时,所有剩余的任务都被取消。
这是我做的一个例子。该任务正在并发工作,但不会在例外情况下中断。
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
List<Future> futures = new ArrayList<Future>();
futures.add(executorService.submit(new Callable<Void>() {
public Void call() throws Exception {
Thread.sleep(5000);
System.out.println("Task 1 done");
return null;
}
}));
futures.add(executorService.submit(new Callable<Void>() {
public Void call() throws Exception {
Thread.sleep(2000);
System.out.println("Task 2 done");
if (true) {
throw new CustomException("Error on task 2");
}
return null;
}
}));
executorService.shutdown();
try {
executeFutures(futures);
} catch (CustomException ex) {
System.out.println("Received:" + ex.getMessage());
executorService.shutdownNow();
}
}
private static void executeFutures(List<Future> futures) throws CustomException {
try {
for (Future f : futures) {
f.get();
}
} catch (ExecutionException | InterruptedException e) {
if (e.getCause() instanceof CustomException) {
throw (CustomException) e.getCause();
}
}
}
}
这是输出:
Task 2 done //exception is thrown here but task1 continue.
Task 1 done
Received:Error on task 2
任何帮助将不胜感激。
你不会在代码的任何地方检查任务1看看如果当前线程被中断。 – Zymus
我同意,但哪里会有关于每个线程失败的信息? ,如果有两个以上的线程在问题发生后抛出。也许我的方法是错误的,但我看不到一个好的方法。 – abdiel
来自文档:除了竭尽全力尝试停止处理主动执行的任务之外,没有任何保证。例如,典型的实现将通过Thread.interrupt()取消,所以任何不能响应中断的任务都不会终止。 - 你需要实际处理任务被中断的情况。当任务2中断时,任务1已经运行。 – pandaadb