我正在尝试让一个关闭挂钩在我的 ubuntu 服务器上工作,但是我似乎遇到了多个线程的问题。使用基本的 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.");
}
}