你可以尝试这样的:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() { /*
my shutdown code here
*/ }
});
编辑:
关机挂钩将不会执行关闭应用程序。相反,它为开发人员提供了他/她希望关闭时进行任何清理的方法。
从JavaDoc for Runtime(如果您打算使用此方法,则会很好阅读):
A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. …