gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:14:42 27 4
gpt4 key购买 nike

/**
* 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;

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

这是否意味着我必须执行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);
}

什么这个方法不等待之前提交的任务
完整执行
是什么意思?即使任务没有完成也发送停止中断?

/**
* 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();

最佳答案

关闭:不再有传入任务。

awaitTermination:在关闭请求后调用。

What does this completed execution after a shutdown mean?

您应该首先调用shutdown。否则,您可能会等待很长时间,因为 awaitTermination 实际上并没有关闭您的执行程序。

Does it mean I have to execute a shutdown API?

是的,如上所述

What does This method does not wait for previously submitted tasks to complete execution mean?

这意味着,shutdown 不是阻塞调用...方法在调用后立即返回。被阻止直到一切完成..您调用awaitTermination

关于java - 我应该调用 `executorService.shutdown` 和 `executorService.awaitTermination` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35970266/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com