我试图在我的ubuntu服务器上使用关闭钩子(Hook),但是似乎有多个线程存在问题。使用基本的ShutdownHook,当我使用kill <PID>终止进程时,以下代码确实起作用,这意味着激活了关机行为。

public static void main(String[] args) {
    ShutdownHook shutDown = new ShutdownHook();
    shutDown.attachShutDownHook();

    while(true){}
}

但是,带有附加线程的相同代码不会
public static void main(String[] args) {
    ShutdownHook shutDown = new ShutdownHook();
    shutDown.attachShutDownHook();

    (new Thread() {
        public void run() {
            while ( true ) {}
        }
    }).start();

    while(true){}
}

有任何想法吗?
class ShutdownHook {

    ShutdownHook() {
    }

    public void attachShutDownHook() {

            Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                            System.out.println("Shut down hook activating");
                    }
            });
            System.out.println("Shut Down Hook Attached.");

    }
}

最佳答案

当仍然有非守护进程线程在运行时,JVM将不会退出。尝试在新线程上调用setDaemon(true)

09-26 20:36