【问题标题】:Java Executor Service waiting for all tasks to complete [duplicate]Java Executor Service等待所有任务完成[重复]
【发布时间】:2018-10-17 14:54:46
【问题描述】:

我正在使用执行器服务来运行我的 10 个任务,一次有 2 个任务。

ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; i++) {
    String name = "NamePrinter " + i;
    Runnable runner = new TaskPrint(name, 1000);
    System.out.println("Adding: " + name + " / " + 1000);
    executor.execute(runner);
}

如何等待所有任务完成

【问题讨论】:

  • 是的,我看到了这个问题,但是添加这一行会立即停止程序 taskExecutor.shutdown();尝试 { taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { ... } 还有,我不知道告诉最大等待时间
  • 然后提交minimal reproducible example。但我猜你在循环中调用了那个方法?!
  • stackoverflow.com/questions/19348248/… taskExecutor.shutdown();答案是停止程序。我不知道为什么有 300 多人支持这个答案

标签: java executorservice


【解决方案1】:

使用java 8 CompleteableFuturejoin方法等待:

ExecutorService executor = Executors.newFixedThreadPool(2);
CompletableFuture[] futures = new CompletableFuture[10];
for (int i = 0; i < 10; i++) {
    String name = "NamePrinter " + i;
    Runnable runner = new TaskPrint(name, 1000);
    System.out.println("Adding: " + name + " / " + 1000);
    futures[i] =  CompletableFuture.runAsync(runner, executor);

}
CompletableFuture.allOf(futures).join(); // THis will wait until all future ready.

【讨论】:

  • 不回答如何使用执行器服务。
  • CompletableFuture 将由 ExecutorService 支持,请参阅我编辑的答案
【解决方案2】:

将您的可调用对象分配给期货,并检查您是否可以从每个期货中获得结果。

        Future future = workerExecutor.submit(new Callable() {
            @Override
            public Object call() throws Exception {
                try {
                    System.out.println("MyItemTree.TimedRunnable");
                    ReturnInterface returnInterface = (ReturnInterface) commandInterface.call();
                    returnInterface.submitResult();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
                return null;
            }
        });

        try {
            Object get = future.get();
        } catch (InterruptedException | ExecutionException ex) {
            Throwable cause = ex.getCause();

            ex.printStackTrace();
            cause.printStackTrace();
            Throwable cause1 = cause.getCause();

            if (cause1 instanceof CommandInterfaceException) {
                System.out.println("[MyItemTree].scheduleTask Cause 1= COMMANDINTERFACE EXCEPTION");
                this.componentInterface.getAlertList().addAlert(((CommandInterfaceException) cause1).getResolverFormInterface());
            }
        }

    }

【讨论】:

  • 执行器服务本身没有那么简单的解决方案吗?
猜你喜欢
  • 1970-01-01
  • 2021-06-12
  • 2011-03-17
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多