【问题标题】:Don't understand ExecutorService#shutdown [duplicate]不理解 ExecutorService#shutdown [重复]
【发布时间】:2018-08-31 09:36:45
【问题描述】:

以下是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();

它说

  1. 不接受新任务
  2. 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");


    }


}

两个任务都提交了,由于池中只有一个线程,所以有一个任务在运行,另一个在队列中等待调度。

但是,这两个任务最终都会运行。

所以,我想问一下 This method does not wait for previously submitted tasks to complete execution 的 javadoc 是什么意思

【问题讨论】:

  • 表示在两个提交的任务完成之前打印“Job is done”。
  • 文档说:启动有序关闭,执行之前提交的任务,但不会接受新任务。您报告的这句话意味着一旦调用shutdown,执行就会继续进行而无需等待。如果您想在不完成活动任务的情况下关闭所有内容,请致电shutdownNow

标签: java


【解决方案1】:

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

【讨论】:

  • 但是,正如我的测试用例所示,这两个任务都完成了。
  • 是的,他们已经完成了,但是 shutdown 方法在他们完成之前返回了。它没有等待。
  • @Tom 您从哪里得知任务无法完成?该语句意味着shutdown 是一个非阻塞调用,它不会阻塞,直到任务完成返回。这并不意味着任务不会完成。
  • 对比shutdownNow,后者取消所有计划任务。
  • 好的,谢谢,也就是说,提交的任务会在池真正关闭之前运行。
猜你喜欢
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
相关资源
最近更新 更多