为什么要在exec.shutdown()之前将exec.isTerminated()与Java中的ExecutorService一起使用?

问题描述 投票:0回答:1

我正在研究线程,并且遇到了以下代码,并有所顾虑

ExecutorService exec = Executors.newFixedThreadPool(2);

exec.execute(left);
exec.executed(right);

if (!exec.isTerminated()) {
    exec.shutdown();
    exec.awaitTermination(5L, TimeUnit.SECONDS);
}

int result = left.getResult() + right.getResult();

如果所有任务都终止,则if条件将为False,并且在if条件之外没有关闭命令,线程池也不会终止。

以下是正确的:

  1. 所以也应该在外面不关机吗?

  2. 为什么还要有if条件,shutdown()等待所有预先提交的任务完成,而我们甚至可以摆脱awaitTermination()?

java threadpool executorservice executor
1个回答
0
投票

没有理由打电话给isTerminated()。从the documentation

请注意,除非首先调用isTerminatedtrue,否则shutdown永远不会是shutdownNow。>

因此,在该代码中exec.isTerminated()始终为假。 if语句是毫无意义的,因为它的主体将始终执行。

[shutdown()方法does not wait for anything:

启动有序关闭,在该顺序中将执行先前提交的任务,但将不接受任何新任务。

因此,awaitTermination调用仍然有用。 (但是假设五秒钟是不安全的;有更好的方法来确保所有提交的任务都已完成。)

© www.soinside.com 2019 - 2024. All rights reserved.