假设我有几个任务要在 Java 中并行运行。每个任务返回成功或失败。每项任务都有一个相关的截止日期。如果任务未在截止日期前完成,则会被中断(所有任务可中断)并返回失败。
如果其中一项任务失败(即返回失败),我们会中断仍在运行的所有其他任务。
我们应该等到所有任务完成,如果所有任务都返回成功,则最终返回成功;如果至少有一个任务返回失败,则最终返回失败。
你会如何实现它?我将使用util.concurrent。您会建议使用哪些库原语?
最佳答案
ExecutorCompletionService 似乎最接近
ExecutorService ex = Executors.newCachedThreadPool();
ExecutorCompletionService<Boolean> cs = new ExecutorCompletionService<Boolean>(
ex);
List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
... add tasks
List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
for (Callable<Boolean> t : tasks) {
futures.add(cs.submit(t));
}
for (!futures.isEmpty()) {
try {
Future<Boolean> f = cs.poll(1, TimeUnit.SECONDS);
futures.remove(f); // poll returns the same instance of Future as in the futures list
if (f == null || !f.get()) { // poll returns null on timeout
break;
}
} catch (Exception e) {
break;
}
}
// cancel remaining tasks, if all finished OK the list will be empty
for (Future<Boolean> future : futures) {
future.cancel(true);
}
关于java - Java 中的并行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899135/