我们什么时候应该在Java中调用System.exit [英] When should we call System.exit in Java

查看:95
本文介绍了我们什么时候应该在Java中调用System.exit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,以下代码中有没有 System.exit(0)有什么区别?

In Java, What is the difference with or without System.exit(0) in following code?

public class TestExit
{      
    public static void main(String[] args)
    { 
        System.out.println("hello world");

        System.exit(0);  // is it necessary? And when it must be called? 
    }      
}

文档说:此方法永远不会正常返回。这是什么意思?

The document says: "This method never returns normally." What does it mean?

推荐答案

System.exit()可用于运行关闭挂钩。这是在较大程序中处理关闭的一种方便方法,其中程序的所有部分都不能(也不应该)彼此了解。然后,如果有人想要退出,他可以简单地调用 System.exit(),并且关闭钩子(如果设置正确)负责做所有必要的关机仪式,如作为关闭文件,释放资源等。

System.exit() can be used to run shutdown hooks before the program quits. This is a convenient way to handle shutdown in bigger programs, where all parts of the program can't (and shouldn't) be aware of each other. Then, if someone wants to quit, he can simply call System.exit(), and the shutdown hooks (if properly set up) take care of doing all necessary shutdown ceremonies such as closing files, releasing resources etc.

此方法永远不会正常返回。意味着该方法不会返回;一旦一个线程进入那里,就不会再回来了。

"This method never returns normally." means just that the method won't return; once a thread goes there, it won't come back.

退出程序的另一种可能是更常见的方法是简单地到达<$的末尾c $ c> main 方法。但是如果有任何非守护程序线程在运行,它们将不会被关闭,因此JVM将不会退出。因此,如果您有任何此类非守护程序线程,则需要一些其他方法(而不是关闭挂钩)来关闭所有非守护程序线程并释放其他资源。如果没有其他非守护程序线程,从 main 返回将关闭JVM并将调用关闭钩子。

Another, maybe more common, way to quit a program is to simply to reach the end of the main method. But if there are any non-daemon threads running, they will not be shut down and thus the JVM will not exit. Thus, if you have any such non-daemon threads, you need some other means (than the shutdown hooks) to shut down all non-daemon threads and release other resources. If there are no other non-daemon threads, returning from main will shut down the JVM and will call the shutdown hooks.

出于某种原因,关闭钩子似乎是一个被低估和误解的机制,人们正在重新发明轮子与所有类型的专有自定义黑客退出他们的程序。我鼓励使用关机钩子;它是标准的运行时中的所有内容无论如何都要用。

For some reason shutdown hooks seem to be an undervalued and misunderstood mechanism, and people are reinventing the wheel with all kind of proprietary custom hacks to quit their programs. I would encourage using shutdown hooks; it's all there in the standard Runtime that you'll be using anyway.

这篇关于我们什么时候应该在Java中调用System.exit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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