处理这个的方法是注册一个
shutdown钩子。如果使用(SIGINT)kill -2会导致程序正常退出并运行关闭挂接。
Registers a new virtual-machine
shutdown hook.
The Java virtual machine shuts down in
response to two kinds of events:
The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.
我试过下面的测试程序在OSX 10.6.3和kill -9它没有运行关闭挂钩,没有想到它会。在kill -15它每次运行关闭挂钩。
public class TestShutdownHook
{
public static void main(final String[] args) throws InterruptedException
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("Shutdown hook ran!");
}
});
while (true)
{
Thread.sleep(1000);
}
}
}
这是编写自己的signal handlers而不是Java中的关闭挂钩的文档化方式。是warned com.sun.misc包和不支持,可以随时更改或消失,并且可能只存在于Sun JVM中。