带有守护线程的 ExecutorService - 显式关闭

ExecutorService with daemon threads - explicit shutdown

如果我设置一个 ExecutorService 和一个生成守护进程线程的 ThreadFactory,我还需要显式调用 shutdown() 方法吗?

Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).build());

嗯,as per setDaemon

The Java Virtual Machine exits when the only threads running are all daemon threads.

因此,因为您使用的是守护线程,所以您的执行程序不会阻止您的应用程序完成。但这并不是说 没有理由 调用 shutdown。您可能仍希望在申请结束前的某个时间点阻止提交任何其他任务。


喜欢的可以试试:(我去掉了Guava的东西,但是原理是一样的)

public static void main(String... args)
{
    final ExecutorService executorService = Executors.newSingleThreadExecutor(r -> {
        final Thread thread = new Thread(r);
        thread.setDaemon(false); //change me
        return thread;
    });
    executorService.submit(() -> { while (true){ System.out.println("busy"); } });
}