使用Allof的Java完整图:如果一个线程引发异常,则如何立即停止执行所有线程?
// assume: serviceCall1 throws an exception after 1s, servserviceCall2 runs 10s without exception
CompletableFuture<String> serviceCall1Future = serviceCall1.execute();
CompletableFuture<String> serviceCall2Future = serviceCall2.execute();
CompletableFuture<Void> allOffFuture = CompletableFuture.allOf(serviceCall1Future, serviceCall2Future);
// does not work, will be called after thread 2 has finished
allOffFuture.exceptionally( ex -> { allOffFuture.cancel(true); return null; } );
try {
// waiting for threads to finish
allOffFuture.join();
} catch (CompletionException e) {
// does not work, here we come after thread 2 has finished
allOffFuture.cancel(true);
}
如果一个线程引发异常,则在我的情况下,对于其他线程保持运行没有任何意义,因此我希望它们俩(在2个以上的线程中)停止。我该如何实现?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想这样的事情应该可以起作用:
当一个人完成时,这会取消另一个未来。
I guess something like this should work:
This cancels the other future when the one completes with an exception.
如果您使用具有完整future的执行权限服务,则可以使用shutdowns方法(例如shutdown()或shutdownnow())。
请参见 - &gt;
If you are using an ExecutorService with CompletableFuture, you can use Shutdowns methods like shutdown() or shutdownNow().
See -> https://jenkov.com/tutorials/java-util-concurrent/executorservice.html#executorservice-shutdown