我有班级SomeService
。它的方法可以从不同的线程调用(例如从RestController)。这个类包含ExecutorService
和一些CustomClass
。
public class SomeService {
private ExecutorService service;
private CustomClass customClass;
public SomeService(ExecutorService service, CustomClass customClass){
this.service = service;
this.customClass = customClass;
}
public void servicePost() {
CountDownLatch countDownLatch = new CountDownLatch(urls.size());
for (String url : List<String> urls){
service.submit(() -> {
customClass.send(url);
countDownLatch.countDown();
});
}
countDownLatch.await();
}
}
我想使用customClass.send(url)
在不同的线程中执行ExecutorService
parallel,但是这个方法可以抛出RuntimeException
。
例如,我提交了5个任务: 1. 2个任务成功执行 2. 2个任务正在运行。 3.其中一个抛出RuntimeException。
如何中断正在运行的任务? 附: ExecutorService可以从其他线程获得任务。我不想打断他们。
当您捕获异常时,可以在执行程序服务上调用shutdownNow()
,还需要在处理之前检查任务内部的Thread#interrupted()
。您的代码应如下所示:
service.submit(() -> {
if (!Thread.interrupted()) {
try {
customClass.send(url);
countDownLatch.countDown();
} catch (Exception e) {
service.shutdownNow();
}
}
});