简体   繁体   English

关机还是不关机? 在ExecutorService(Java8)中

[英]Shutdown or Not Shutdown? in ExecutorService (Java8)

I am trying to understand the behaviour of the executor service relative to shutdown. 我试图了解执行程序服务相对于关闭的行为。 The documentation says that the application won't terminate unless there is a shutdown() call - but in this simple example. 文档说除非有shutdown()调用,否则应用程序不会终止 - 但在这个简单的例子中。 It exits after one minute precisely. 它精确地在一分钟后退出。 Any idea? 任何的想法?

 Runnable r = new Runnable() {
            @Override
            public void run() {
                Print.println("do nothing");
            }
        };
        ThreadFactory TF = (Runnable run) -> new Thread(run);
        ExecutorService exec = Executors.newCachedThreadPool(TF);
        exec.submit(r);

returns this: 11:34:00.421 : Thread-0: do nothing BUILD SUCCESSFUL (total time: 1 minute 0 seconds) 返回:11:34:00.421:线程-0:什么都不做构建成功(总时间:1分0秒)

You are using CachedThreadPool. 您正在使用CachedThreadPool。 It keeps the thread alive for 60 secs so that next subsequent tasks do not waste time in creating new thread resource. 它使线程保持活动60秒,以便下一个后续任务不会浪费时间来创建新的线程资源。 http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html

The internal code - 内部代码 -

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

You should call shutdown() once the job is done. 作业完成后,您应该调用shutdown()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM