在 java 关闭挂钩中添加守护线程与非守护线程的区别
Difference in adding a daemon vs non-daemon thread in a java shutdown hook
我在 Whosebug 中看到了这个讨论。但是我不清楚 ShutdownHook
中将线程标记为守护进程是否与将其标记为非守护进程相同?
Thread t = new Thread(this::someMethod, "shutdown_hook");
t.setDaemon(true);
Runtime.getRuntime().addShutdownHook(t);
如果我不在上面的代码中执行 t.setDaemon(true);
,行为是否相同。
我正在使用 java 8.
关闭钩子线程是否是守护进程没有区别。
正如 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
启动挂钩线程并等待所有线程完成:
for (Thread hook : threads) {
hook.start();
}
for (Thread hook : threads) {
while (true) {
try {
hook.join();
break;
} catch (InterruptedException ignored) {
}
}
}
我在 Whosebug 中看到了这个讨论。但是我不清楚 ShutdownHook
中将线程标记为守护进程是否与将其标记为非守护进程相同?
Thread t = new Thread(this::someMethod, "shutdown_hook");
t.setDaemon(true);
Runtime.getRuntime().addShutdownHook(t);
如果我不在上面的代码中执行 t.setDaemon(true);
,行为是否相同。
我正在使用 java 8.
关闭钩子线程是否是守护进程没有区别。
正如 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
启动挂钩线程并等待所有线程完成:
for (Thread hook : threads) {
hook.start();
}
for (Thread hook : threads) {
while (true) {
try {
hook.join();
break;
} catch (InterruptedException ignored) {
}
}
}