正确结束Java命令行应用程序 [英] End Java command line application properly

查看:213
本文介绍了正确结束Java命令行应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道。在Java命令行应用程序的 main 方法结束之前,是否需要调用 System.exit(0); 如果是这样,为什么?如果我总是把它放在那里 0 ,它与它自己退出的区别是什么?什么是不清理?



在此先感谢。

解决方案

没有!您并不总是需要调用 System.exit(0)来结束一个java程序。如果您的代码没有生成非守护线程,则应用程序将在完成主线程任务后自动终止。 如果你的main方法产生了一些非守护线程,它们在你的main方法到达最后时仍然在进行一些处理,那么应用程序不会被终止直到这些线程完成。在这种情况下,如果您明确地调用 System.exit(0),那么应用程序将立即终止并终止所有线程。



请参阅主题的javadoc 其中提到了细节。


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.

解决方案

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.

这篇关于正确结束Java命令行应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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