在Java中,如何等待所有任务,但停止第一个错误? [英] In Java, how do I wait for all tasks, but halt on first error?

查看:119
本文介绍了在Java中,如何等待所有任务,但停止第一个错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列的并行任务要运行。如果其中任何一个失败,我想中断他们,等待终止。



ExecutorCompletionService似乎几乎是我想要的,但似乎没有出现一种方法来告诉我是否所有的任务都完成了,除了保持一个单独的计数任务数。 (请注意,ExecutorCompletionService的Javadoc中的两个示例都会跟踪任务的计数n,并使用它来确定服务是否已完成。)


解决方案

是的,你需要保持跟踪如果你使用ExecutorCompletionService。通常,你会在futures上调用get()来查看是否发生错误。没有迭代的任务,你怎么能告诉那个失败了?


I have a series of concurrent tasks to run. If any one of them fails, I want to interrupt them all and await termination. But assuming none of them fail, I want to wait for all of them to finish.

ExecutorCompletionService seems like almost what I want here, but there doesn't appear to be a way to tell if all of my tasks are done, except by keeping a separate count of the number of tasks. (Note that both of the examples of in the Javadoc for ExecutorCompletionService keep track of the count "n" of the tasks, and use that to determine if the service is finished.)

Am I overlooking something, or do I really have to write this code myself?

解决方案

Yes, you do need to keep track if you're using an ExecutorCompletionService. Typically, you would call get() on the futures to see if an error occurred. Without iterating over the tasks, how else could you tell that one failed?

这篇关于在Java中,如何等待所有任务,但停止第一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆