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

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

问题描述

我对优雅地关闭 Java 命令行程序的不同方法感兴趣.发送终止信号不是一种选择.

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. 观察要创建的文件,然后关闭.
  3. 从终端读取一些输入,例如执行关机".

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

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?

推荐答案

你可以试试这样的:

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.

来自 JavaDoc for 运行时(如果您打算使用此方法,请阅读此书):

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天全站免登陆