JAVA:当进程停止时如何调用方法(甚至可能吗?)
我希望这样,当我的用户从命令行启动我的程序,然后终止进程(例如 ctrl+c)时,程序将通过关闭其所有连接来正常关闭。 这可能吗? 我不能像 GUI 那样在关闭时调用一个方法吗? 该程序没有 GUI。
请告诉我。
I want it so when my users start my program from the command line and then kill the process (ctrl+c, for example) the program will shutdown gracefully by closing all its connections. Is this even possible? I can't just have it call a method upon closing like a GUI can? This program has no GUI.
Please let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里是关于 Java 信号处理的非常好的指南。 它还涵盖关闭和终止情况,包括 Ctrl-C。
您想要的具体调用是在运行时中, addShutdownHook。
仍然存在您无法处理的特定情况...通常某种操作系统可以通过某种方式直接终止应用程序而不给它自我保存的机会。 通过这种机制你无法覆盖所有情况。 引用JavaDoc
Here is a pretty good guide to signal handling in Java. It covers shutdown and termination cases as well, including Ctrl-C.
The specific call you want is in the Runtime, addShutdownHook.
There are still specific cases that you cannot handle... there is usually some way for the OS to just outright kill the application without giving it a chance to save itself. You can't cover every case through this mechanism. To quote the JavaDoc