Java Executor Service等待所有任务完成

时间:2018-05-07 18:23:48

标签: java executorservice

我正在使用执行程序服务来一次运行我的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);
}

我如何等待所有任务完成

2 个答案:

答案 0 :(得分:2)

使用带有CompleteableFuture方法的java 8 join等待:

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.

答案 1 :(得分:0)

将您的callable分配给期货,并检查您是否可以从每个未来获得结果。

        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());
            }
        }

    }