Here is a pretty good guide to signal handling in Java。它还涵盖关闭和终止情况,包括Ctrl-C。
您想要的特定呼叫位于运行时间addShutdownHook中。
还有一些你不能处理的具体情况......操作系统通常会以某种方式直接杀死应用程序而不给它一个自我保存的机会。你无法通过这种机制来覆盖每一个案例。引用JavaDoc
In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.