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

查看:26
本文介绍了我们什么时候应该在 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.

另一种可能更常见的退出程序的方法是简单地到达 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天全站免登陆