gpt4 book ai didi

java - 在 java shutdown hook 中添加守护线程与非守护线程的区别

转载 作者:行者123 更新时间:2023-12-01 20:08:47 26 4
gpt4 key购买 nike

我在stackoverflow中看到过这个讨论。但我不清楚在 ShutdownHook 中将线程标记为守护进程是否与将其标记为非守护进程相同?

Thread t = new Thread(this::someMethod, "shutdown_hook");
t.setDaemon(true);
Runtime.getRuntime().addShutdownHook(t);

如果我不在上面的代码中执行 t.setDaemon(true); ,行为是否会相同。

我使用的是java 8。

最佳答案

无论关闭钩子(Hook)线程是否为守护进程,都没有区别。

作为 Runtime.addShutdownHook 的规范说,

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method.

Once the shutdown sequence has begun it can be stopped only by invoking the halt method

JDK 实现遵循这些规则。正如我们在 source code 中看到的那样, runHooks 启动钩子(Hook)线程并等待所有线程完成:

    for (Thread hook : threads) {
hook.start();
}
for (Thread hook : threads) {
while (true) {
try {
hook.join();
break;
} catch (InterruptedException ignored) {
}
}
}

关于java - 在 java shutdown hook 中添加守护线程与非守护线程的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58972594/

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