gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:15:52 27 4
gpt4 key购买 nike

如果我设置一个 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"); } });
}

关于java - 带有守护线程的 ExecutorService - 显式关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50296223/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com