有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java关闭挂钩中添加守护进程与非守护进程线程的区别

我在{a1}中看到了这一讨论。但我不清楚在ShutdownHook中将线程标记为守护进程是否与将其标记为非守护进程相同

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

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

我正在使用Java8


共 (1) 个答案

  1. # 1 楼答案

    不管关闭钩子线程是否是守护进程,都没有区别

    正如^{}的规范所说

    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) {
                }
            }
        }