java - Java 中的并行任务

标签 java multithreading concurrency java.util.concurrent

假设我有几个任务要在 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/

相关文章:

performance - 使用集群和 node-webworker 构建高性能 node.js 应用程序

java - 跟踪通过 Java Web Start 启动的客户端应用程序的关闭

java - 使用 ANT 任务时将文件传递到 antfile

java - 如何防止 CompletableFuture#whenComplete 在上下文线程中执行

java - 关于java线程生命周期

c++ - 多线程合并排序的奇怪结果

java - 优雅地为 ExecutorServices 实现队列长度指示器

java - 我如何在java中组织这个多边形列表以便它们易于使用?

java - Swing:将数据从 JFrame 传递到另一个 JFrame

c - 如果多个线程并行处理,如何维护数据包的顺序?