首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不懂ExecutorService#shutdown

不懂ExecutorService#shutdown
EN

Stack Overflow用户
提问于 2018-08-31 09:36:45
回答 1查看 71关注 0票数 0

下面是ExecutorService#shutdown的javadoc

代码语言:javascript
运行
复制
/**
 * 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();

上面写着

  1. 不接受新任务
  2. NOT会等待提交的任务完成吗?

我对第一点毫不怀疑,但我认为执行者将等待提交的任务完成,就像下面的代码一样:

代码语言:javascript
运行
复制
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是什么意思

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-31 09:41:22

这意味着shutdown方法将立即返回。在返回调用方之前,它不会等待已排定和已经运行的任务完成。这意味着ExecutorService仍然需要一些时间来清理和终止自身(在所有正在运行的任务完成之后,它最终都会这样做)。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52112558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档