我什么时候需要调用此方法Runtime.getRuntime()。addShutdownHook() [英] When do I need to call this method Runtime.getRuntime().addShutdownHook()

查看:481
本文介绍了我什么时候需要调用此方法Runtime.getRuntime()。addShutdownHook()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我什么时候需要调用此方法Runtime.getRuntime()。addShutdownHook()以及何时或为何需要关闭我的应用程序。任何人都可以通过举一些例子来解释我。

When do I actually need call this method Runtime.getRuntime().addShutdownHook() and when or why I need to shutdown my application. Could anyone please explain me this by giving some example.

谢谢

推荐答案

据我所知,我将在下面解释。您可以谷歌搜索并查找大量信息。

As far as I know, I will explain this below. You can google it and find lot of information too.

addShutdownHook()将注册一些操作在程序终止时执行。您开始的程序以两种方式结束:

addShutdownHook() will register some actions which is to be performed on a Program's termination. The program that you start ends in two ways:


  1. 主线程(Root)结束其运行上下文;

  2. 程序遇到一些意想不到的情况,因此无法继续进行。

如果添加ShutdownHook,钩子将启动一个只在终止时开始运行的线程。例如:

If you add a ShutdownHook, the hook will start a thread that will start running at time of termination only. For example:

 Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        System.out.println("Running Shutdown Hook");
      }
    });

将打印运行关机挂钩程序在任何时候终止的时间。你甚至可以调用 System.exit(0)

will print a Running Shutdown Hook at the time of program termination at any point. You might even call a System.exit(0).

例如,你可以google,有足够的他们问题'你什么时候应该使用它'就像在 try-catch 语句中询问'code> catch 做什么'。

For examples, you can google, there are enough of them. And the question 'When should you use this' is like asking 'What does catch do in a try-catch statement'.

您可能有很多情况,例如:

You might have many situations like:


  • 您的程序已创建文件系统中的许多临时文件要删除它;

  • 您需要在终止之前向另一个进程/机器发送遇险信号;

  • 执行任何对意外行为的清理操作,记录或错误后操作。

所有这些都需要一段时间。

All this will be needed for some point of time.

例如,您可以访问示例1 示例2

这篇关于我什么时候需要调用此方法Runtime.getRuntime()。addShutdownHook()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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