我試圖讓一個關機掛鉤在我的Ubuntu服務器上工作,但是我似乎遇到了多個線程的問題。使用基本的ShutdownHook,當我使用kill <PID>
殺死進程時,下面的代碼會起作用,這意味着關閉行爲被激活。與多個線程的Java關機掛鉤
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.");
}
}
第二個線程的行爲是什麼?沒有調用關閉行爲,應用程序是否停止?你也說「殺死進程」。你是什麼意思?你怎麼終止它? – Gray
第二個線程只是活動線程的一個例子。在我的實際示例中,它正在監聽端口上的連接,並在該程序的整個生命週期中保持活動狀態。我正在用'kill'終止這個過程。上面的第二個程序不能正常工作,所以我在多個線程中丟失了一些東西 –
Reese
嘗試在調用'kill'來查看哪些線程仍在運行後運行'jstack'。 –
SimonC