我正在使用 Callable 和 ExecutorService 在我的应用程序中使用多线程。
如果一个线程抛出任何异常,则需要停止所有线程,即使它已完成工作,也需要将该异常抛给调用类方法。为此,我使用了 shutDownNow() 方法。
这是正确的方法吗?或者还有其他有效的方法吗?
ExecutorService exSvc = Executors.newFixedThreadPool(5);
exSvc.setKeepAliveTime(60, TimeUnit.SECONDS);
List<Future<Integer>> futureList = new LinkedList();
for(int i=0; i<50;i++){
futureList.add(exSvc.submit(
new Callable<Integer>() {
public Integer call() throws Exception{
int num = new Random().nextInt(1000);
if(num==500){
throw new Exception("Error");
}
return num;
}
}));
}
for(int i=0; i<50; i++){
try {
int value = futureList.get(i).get();
} catch (Exception e) {
exSvc.shutdownNow();
throw new Exception("Error");
}
}
最佳答案
正如ciamei所说,如果你想尽早检测到异常,也许你可以使用CountDownLatch :
CountDownLatch cdl = new CountDownLatch(1);
AtomicInteger successCount = new AtomicInteger();
AtomicBoolean fail = new AtomicBoolean();
int taskSize = 50;
for(int i=0; i<taskSize;i++){
futureList.add(exSvc.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(1000);
if(num == 500){
fail.set(true);
cdl.countDown();
throw new Exception("Error");
}
if (successCount.incrementAndGet() == taskSize) {
cdl.countDown();
}
return num;
}
}));
}
try {
cdl.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (fail.get()) {
exSvc.shutdownNow();
throw new Exception("Error");
}
//...
关于java - 如何在一个线程中发生异常后停止可调用线程进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70577347/