【发布时间】:2022-01-04 10:31:04
【问题描述】:
我正在使用 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");
}
}
【问题讨论】:
标签: java multithreading exception concurrency