35

是否可以编写一个 System.exit 在终止程序时调用的方法?

4

5 回答 5

60

使用Runtime.getRuntime().addShutdownHook(Thread).

于 2011-04-21T17:49:45.707 回答
6

关机钩子就是答案……这里有一篇关于它们的文章。它们并非没有问题(其中一些在文章中进行了讨论)。

于 2011-04-21T17:52:00.817 回答
3

您可以使用关闭挂钩。

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread )

请注意,如果 VM 异常中止或调用 Runtime.halt(int),则关闭挂钩将不会运行。

于 2011-04-21T17:51:00.340 回答
2

查看关闭挂钩,请参阅http://docs.oracle.com/javase/8/docs/technotes/guides/lang/hook-design.html

于 2011-04-21T17:49:11.467 回答
2

您可以添加一个VM 关闭挂钩

于 2011-04-21T17:49:48.050 回答