有没有办法在控制台应用程序中监听终止信号? 是否可以在用户停止之前向用户发送消息?
答案 0 :(得分:2)
您可以使用Runtime.html#addShutdownHook(java.lang.Thread)
public class JVMShutdownHookTest {
public static void main(String[] args) {
JVMShutdownHook jvmShutdownHook = new JVMShutdownHook();
Runtime.getRuntime().addShutdownHook(jvmShutdownHook);
System.out.println("JVM Shutdown Hook Registered.");
System.out.println("Pre exit.");
System.exit(0);
System.out.println("Post exit.");
}
private static class JVMShutdownHook extends Thread {
public void run() {
System.out.println("JVM Shutdown Hook: Thread initiated.");
}
}
}
Output:
JVM Shutdown Hook Registered.
Pre exit.
JVM Shutdown Hook: Thread initiated.
了解更多here
答案 1 :(得分:1)
您可以使用java.lang.Runtime.addShutdownHook(Thread)
在JVM关闭过程之前运行一些代码......
答案 2 :(得分:0)
您可以使用本机代码,如here
所述