以下是ExecutorService#shutdown
的javadoc
/**
* 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.
*
* @throws SecurityException if a security manager exists and
* shutting down this ExecutorService may manipulate
* threads that the caller is not permitted to modify
* because it does not hold {@link
* java.lang.RuntimePermission}{@code ("modifyThread")},
* or the security manager's {@code checkAccess} method
* denies access.
*/
void shutdown();
上面写着
- 不会接受新任务
- 威尔
NOT
等待提交的任务完成
我对第一点没有疑问,但我认为执行器会等待提交的任务完成,如下面的代码:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(1);
es.submit(new Runnable() {
@Override
public void run() {
System.out.println("starts to run 1");
try {
Thread.sleep(10 * 1000);
System.out.println("end to run 1");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
es.submit(new Runnable() {
@Override
public void run() {
System.out.println("starts to run 2");
try {
Thread.sleep(10 * 1000);
System.out.println("end to run 2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread.sleep(1 * 1000);
es.shutdown();
System.out.println("Job is done");
}
}
两个任务都提交了,由于池中只有一个线程,所以有一个任务正在运行,另一个在队列中等待调度。
但是,这两个任务最终都会运行。
所以,我想问javadoc This method does not wait for previously submitted tasks to complete execution
是什么意思?
最佳答案
这意味着shutdown
方法立即返回。在返回调用者之前,它不会等待计划的和已运行的任务完成。这意味着 ExecutorService 仍然需要一些时间来清理并终止自身(在所有正在运行的任务完成后,它最终会这样做)。
关于java - 不明白ExecutorService#shutdown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52112558/