我应该调用`executorService.shutdown`和`executorService.awaitTermination`吗?

时间:2016-03-13 12:30:15

标签: java multithreading interrupt executorservice

/**
 * Blocks until all tasks have completed execution after a shutdown
 * request, or the timeout occurs, or the current thread is
 * interrupted, whichever happens first.
 *
 * @param timeout the maximum time to wait
 * @param unit the time unit of the timeout argument
 * @return {@code true} if this executor terminated and
 *         {@code false} if the timeout elapsed before termination
 * @throws InterruptedException if interrupted while waiting
 */
boolean awaitTermination(long timeout, TimeUnit unit)
    throws InterruptedException;

completed execution after a shutdown是什么意思?

这是否意味着我必须执行shutdown API?

我的代码应该是这样的:

@Test
public void setUserNamePropertyFromMultiThreadsUpdatesCorrectly() throws Exception {
        ..

        List<Callable<Void>> callables = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            callables.add(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    ..
                    assertTrue(isSuccess);
                    return null;
                }
            });
        }
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        try {
            executorService.invokeAll(callables);
            executorService.shutdown();
            executorService.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

   ..
}

 try {
                executorService.invokeAll(callables);
                executorService.awaitTermination(1, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }

This method does not wait for previously submitted tasks to complete execution是什么意思?即使任务没有完成,也会发送停止中断?

/**
 * Initiates an orderly shutdown in which previously submitted
 * tasks are executed, but no new tasks will be accepted.
 * Invocation has no additional effect if already shut down.
 *
 * <p>This method does not wait for previously submitted tasks to
 * complete execution.  Use {@link #awaitTermination awaitTermination}
 * to do that.
 */
void shutdown();

1 个答案:

答案 0 :(得分:1)

shutdown:不再有传入的任务。

awaitTermination:在关机请求后调用。

  

关闭后这完成执行的意思是什么?

您应该先致电shutdown。否则,您可能需要等待很长时间,因为awaitTermination实际上并没有关闭执行程序。

  

这是否意味着我必须执行关机API?

是的,如上所述

  

此方法不会等待以前提交的任务        完全执行意味着什么?

这意味着,shutdown不是阻塞调用...方法在调用后立即返回。要阻止,直到一切都完成..你打电话给awaitTermination