简体   繁体   English

ExecutorService关闭钩子

[英]ExecutorService shutdown hook

I have console application with following threading code. 我有以下线程代码的控制台应用程序。 It seems when i hit Ctrl+C to terminate it does not detect control keys, i have to close command prompt window. 看来当我按Ctrl + C终止它没有检测到控制键时,我必须关闭命令提示符窗口。

Any clues why it is not detecting ctrl+c? 任何线索为什么它没有检测到ctrl + c?

            final ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
        final long SHUTDOWN_TIME = TimeUnit.SECONDS.toMillis(10);
        for (int i = 0; i < threadPoolSize; i++) {
            executor.submit(new MessageWorker(topicSubscriber));
        }
        //--
        //Add JVM shutdown hook
        Runtime.getRuntime().addShutdownHook(new Thread() {
            /**
             * @see java.lang.Thread#run()
             */
            @Override
            public void run() {
                executor.shutdown();
                try {
                    if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) {
                        log.warn("Executor did not terminate in the specified time.");
                        List<Runnable> droppedTasks = executor.shutdownNow();
                        log.warn("Executor was abruptly shut down. " + droppedTasks.size() + " tasks will not be executed.");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

Just a guess from reading the code, but, it looks like your shutdown time is set as 10,000 seconds, so I'm not surprised you don't think it's quitting! 只是从阅读代码猜测,但是,看起来您的关机时间设置为10,000秒,所以我不会惊讶你不认为它会退出!

    final long SHUTDOWN_TIME = TimeUnit.SECONDS.toMillis(10);
    ...
    if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) {

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

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