以下是您可以考虑的事情。这里我使用CallableTask而不是Thread。
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Set<Future<Void>> futureSet = new HashSet<Future<Void>>();
for (int i = 0; i < 9; i++) {
CallableTask1 task = new CallableTask1();
futureSet.add(executorService.submit(task));
}
CallableTask2 task2 = new CallableTask2();
futureSet.add(executorService.submit(task2));
boolean flag = false;
for (Future<Void> future : futureSet) {
try {
future.get();
} catch (InterruptedException e) {
System.out.println("Interrupted");
} catch (ExecutionException e) {
System.out.println("Exception thrown from the thread");
flag = true;
break;
}
}
if(flag) {
for (Future<Void> future : futureSet) {
future.cancel(true);
}
}
}
这里我使用了两个类来演示这个工作。当一个任务抛出异常时,永远运行的任务也停止运行。
class CallableTask1 implements Callable<Void> {
@Override
public Void call() throws Exception {
throw new NullPointerException("Sample NullPointerException");
}
}
class CallableTask2 implements Callable<Void> {
@Override
public Void call() throws Exception {
while (true){
System.out.println("THIS IS RUNNING");
Thread.sleep(5000);
}
}
}
但这有它自己的局限性。由于“future.get()”顺序执行,此代码将等待轮到抛出异常。
最佳案例:在第一个future.get()中抛出异常,其他任务将被取消。
最糟糕的情况:在上一个future.get()中抛出一个异常,并由时间抛出异常执行所有其他任务。
优化:确定可以抛出异常并等待这些任务仅用于取消所有其他任务的任务。
如果你的跑步方法有,那么最好的方式是共享一个标志并打破它。有关更多信息,请检查this答案。
感谢您的解决方案和指针,它看起来很棒。我正在处理你的建议。 –