简体   繁体   English

程序在java中退出时调用函数

[英]Calling function when program exits in java

I would like to save the programs settings every time the user exits the program. 我想在每次用户退出程序时保存程序设置。 So I need a way to call a function when the user quits the program. 所以当用户退出程序时我需要一种方法来调用函数。 How do I do that? 我怎么做?

I am using Java 1.5. 我使用的是Java 1.5。

You can add a shutdown hook to your application by doing the following: 您可以通过执行以下操作向应用程序添加关闭挂钩:

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    public void run() {
        // what you want to do
    }
}));

This is basically equivalent to having a try {} finally {} block around your entire program, and basically encompasses what's in the finally block. 这基本上相当于在整个程序中使用try {} finally {}块,并且基本上包含了finally块中的内容。

Please note the caveats though! 请注意警告

Adding a shutdown hook addShutdownHook(java.lang.Thread) is probably what you look for. 添加一个关闭钩子addShutdownHook(java.lang.Thread)可能就是你要找的东西。 There are problems with that approach, though: 但是,这种方法存在问题:

  • you will lose the changes if the program aborts in an uncontrolled way (ie if it is killed) 如果程序以不受控制的方式中止(即如果它被杀死),你将失去更改
  • you will lose the changes if there are errors (permission denied, disk full, network errors) 如果有错误(权限被拒绝,磁盘已满,网络错误),您将丢失更改

So it might be better to save settings immediately (possibly in an extra thread, to avoid waiting times). 因此,最好立即保存设置(可能在额外的线程中,以避免等待时间)。

Are you creating a stand alone GUI app (ie Swing)? 你在创建一个独立的GUI应用程序(即Swing)吗?

If so, you should consider how you are providing options to your users how to exit the application. 如果是这样,您应该考虑如何为用户提供如何退出应用程序的选项。 Namely, if there is going to be a File menu, I would expect that there will be an "Exit" menu item. 也就是说,如果有一个文件菜单,我希望会有一个“退出”菜单项。 Also, if the user closes the last window in the app, I would also expect it to exit the application. 此外,如果用户关闭应用程序中的最后一个窗口,我也希望它退出应用程序。 In both cases, it should call code that handles saving the user's preferences. 在这两种情况下,它都应该调用处理保存用户首选项的代码。

Using Runtime.getRuntime().addShutdownHook() is certainly a way to do this - but if you are writing Swing applications, I strongly recommend that you take a look at JSR 296 (Swing Application Framework) 使用Runtime.getRuntime()。addShutdownHook()肯定是一种方法 - 但是如果你正在编写Swing应用程序,我强烈建议你看一下JSR 296(Swing应用程序框架)

Here's a good article on the basics: http://java.sun.com/developer/technicalArticles/javase/swingappfr/ . 这是一篇关于基础知识的好文章: http//java.sun.com/developer/technicalArticles/javase/swingappfr/

The JSR reference implementation provides the kind of features that you are looking for at a higher level of abstraction than adding shutdown hooks. 与添加关闭挂钩相比,JSR参考实现提供了更高抽象级别所需的功能。

Here is the reference implementation: https://appframework.dev.java.net/ 以下是参考实现: https//appframework.dev.java.net/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM