关机还是不关机?在ExecutorService(Java8)中 [英] Shutdown or Not Shutdown? in ExecutorService (Java8)

查看:84
本文介绍了关机还是不关机?在ExecutorService(Java8)中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解执行程序服务相对于关机的行为.该文档说,除非有shutdown()调用,否则应用程序不会终止-但是在此简单示例中.恰好在一分钟后退出.有什么主意吗?

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. 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);

返回以下内容: 11:34:00.421:线程-0:什么都不做 建立成功(总时间:1分0秒)

returns this: 11:34:00.421 : Thread-0: do nothing BUILD SUCCESSFUL (total time: 1 minute 0 seconds)

推荐答案

您正在使用CachedThreadPool.它使线程保持活动状态60秒钟,以便后续的后续任务不会浪费时间来创建新的线程资源. http://docs.oracle.com/javase /7/docs/api/java/util/concurrent/Executors.html

You are using CachedThreadPool. It keeps the thread alive for 60 secs so that next subsequent tasks do not waste time in creating new thread resource. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html

内部代码-

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

作业完成后,您应该调用shutdown().

You should call shutdown() once the job is done.

这篇关于关机还是不关机?在ExecutorService(Java8)中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆