java里利用addShutdownHook可以添加一个
线程,在jvm关闭时调用,执行一些清理工作
class="java" name="code">public static void main(String[] args) throws InterruptedException {
Thread shutdownHook = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("jvm going down!do something here!");
}
});
Runtime.getRuntime().addShutdownHook(shutdownHook);
while (true) {
TimeUnit.SECONDS.sleep(1);
}
}
但是这个线程不能保证总是工作.
引用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.
所以kill -9的时候,就不能保证这个清理函数的执行了