正确结束 Java 命令行应用程序
我只是想知道。我是否需要在 Java 命令行应用程序的 main
方法结束之前调用 System.exit(0);
?如果是这样,为什么?如果我总是把 0
放在那里,与让它自行退出有什么区别?什么没清理干净?
提前致谢。
I am just wondering. Do I need to call System.exit(0);
right before main
method of a Java command line application ends? If so, why? What is the difference from letting it exit on its own, if I would just always put there 0
? What is not cleaned up?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不!您并不总是需要调用 System.exit(0) 来结束 java 程序。如果您的代码没有生成非守护线程,则应用程序将在完成主线程任务后自动终止。
如果您的 main 方法导致生成一些非守护线程,当您的 main 方法已到达末尾时,这些线程仍然处于活动状态,正在执行某些处理,那么在这些线程完成之前,应用程序将不会终止。在这种情况下,如果您显式调用
System.exit(0)
,那么应用程序将立即终止并杀死所有线程。请参考Thread的javadoc,其中提到了细节。
No! You do not always need to call
System.exit(0)
to end a java program. If there is no non-daemon thread spawned by your code, the application will terminate automatically upon finishing your main thread task.If your main method results in spawning some non-daemon thread which are still alive doing some processing while your main method has reached the end, then the application will not be terminated until those threads complete. In this case, if you explicitly call
System.exit(0)
, then application will terminate immediately killing all your threads.Please refer javadoc of Thread which mentions the details.
无需调用
System.exit()
,只需从main()
返回即可。这是退出 Java 程序的常见习惯用法。通常调用 System.exit() 来终止应用程序(这通常意味着由于致命错误而异常终止)。
No need to call
System.exit()
, just return frommain()
. This is the normal idiom for exiting from a Java program.System.exit()
is usually called to terminate an app in the middle of things (which usually means abnormal termination due to a fatal error).