正式关闭Java命令行程序的最佳方法 [英] Best Way to Gracefully Shutdown a Java Command Line Program

查看:173
本文介绍了正式关闭Java命令行程序的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣使用不同的方法来优雅地关闭Java命令行程序。发送kill信号不是一个选项。

I'm interested in different approaches to gracefully shutting down a Java command line program. Sending a kill signal is not an option.

我可以想到几种不同的方法。

I can think of a few different approaches.


  1. 打开端口等待连接。

  2. 从终端读取一些输入,例如execute shutdown

第三个是不理想的,因为经常有程序输出被泵送到屏幕。第一个需要太多的努力(我懒惰)。大多数程序员都使用第二个选项吗?如果没有,还有什么可能/优雅/简单?

The third one is not ideal, since there is often program output pumped to the screen. The first one takes too much effort (I'm lazy). Do most programmers use the second option? If not, what else is possible/elegant/simple?

提前感谢。
Mike

Thanks in advance. Mike

推荐答案

您可以尝试这样:

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { /*
       my shutdown code here
    */ }
 });

编辑

关闭挂接将不会执行关闭应用程序。相反,它给予开发者一种执行他/她希望在关机时的任何清理的方式。

the shutdown hook will not perform the shutting down of the app. instead, it gives the developer a way to perform any clean-up that he/she wishes at shutdown.

。 html#addShutdownHook(java.lang.Thread)rel =nofollow noreferrer>运行时(如果你计划使用这个方法,这是一个很好的阅读):

from the JavaDoc for Runtime (a good read if you are planning to use this method):

关闭挂钩只是一个初始化但未启动的线程。当虚拟机开始其关闭序列时,它将以一些未指定的顺序启动所有注册的关闭挂接,并让它们同时运行。当所有挂钩完成后,如果启用了退出结束,它将运行所有未被挂起的终结器。最后,虚拟机将停止。 ...

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. ...

这篇关于正式关闭Java命令行程序的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆