线程池到底该怎么关闭

2020-04-25  本文已影响0人  江江的大猪
    // 真正的工程不该使用Executors中快捷方法创建的线程池,这里只是演示作用
    private static ExecutorService executorService = Executors.newCachedThreadPool();
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            executorService.shutdown();
            try {
                while (!executorService.awaitTermination(1, TimeUnit.SECONDS)) {
                    System.out.println("还没执行完");
                }
            } catch (InterruptedException e) {
                // 忽略,执行这段逻辑的是jvm关闭的钩子线程,不用考虑中断问题
            }
        }));
    }
//getExitingExecutorService会把线程池中的线程都改为守护线程,并且在jvm关闭时的钩子线程中执行shutDown和awaitTermination
//awaitTermination方法返回只有,不论线程池中的任务执没执行完,因为钩子线程已经执行完了,此时jvm中应该只剩下线程池的守护线程,所以这些守护线程也就随着jvm的关闭结束了
MoreExecutors.getExitingExecutorService(new ThreadPoolExecutor(5, 5, 10, TimeUnit.SECONDS, new LinkedBlockingDeque<>(10)))
        executor.setThreadFactory(new ThreadFactoryBuilder()
                .setDaemon(true)
                .setThreadFactory(executor.getThreadFactory())
                .build());
        addShutdownHook(MoreExecutors.newThread("DelayedShutdownHook-for-" + service, new Runnable() {
            @Override
            public void run() {
                try {
                    // We'd like to log progress and failures that may arise in the
                    // following code, but unfortunately the behavior of logging
                    // is undefined in shutdown hooks.
                    // This is because the logging code installs a shutdown hook of its
                    // own. See Cleaner class inside {@link LogManager}.
                    service.shutdown();
                    service.awaitTermination(terminationTimeout, timeUnit);
                } catch (InterruptedException ignored) {
                    // We're shutting down anyway, so just ignore.
                }
            }
        }));
上一篇 下一篇

猜你喜欢

热点阅读