ExecutorService关闭钩子

时间:2012-12-20 06:10:33

标签: java multithreading concurrency threadpool

我有以下线程代码的控制台应用程序。看来当我点击 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();
                }
            }
        });

1 个答案:

答案 0 :(得分:8)

只是从阅读代码中猜测,但是,看起来您的关机时间设置为10,000秒,所以我不会感到惊讶你不认为它已经退出了!

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