主要功能不返回任何东西。为什么? [英] main function does not return anything. Why?

查看:160
本文介绍了主要功能不返回任何东西。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于C / C ++的main()必须返回一个整数(零表示成功,非零表示失败)。作为程序运行它成为一个过程中,我能理解这一点,每个过程应该有一个退出状态,这是我们做的回声$获得?从后壳的过程中得到了过来。

With respect to C/C++ main() must always return an integer(zero to indicate success and non-zero to indicate failure). I can understand this as the program is run it becomes a process and every process should have an exit status, which we obtain by doing echo $? from shell after the process gets over.

现在我不明白,为什么是其主要方法不会在Java中返回任何东西?它是否有任何与该程序是在JVM上运行和JVM进程reposnsible为退出状态返回?

Now I don't understand why is the main method does not return anything in Java? Has it got anything to do with the fact that the program is run on JVM and the JVM process is reposnsible for the returning of exit status?

请澄清一下。

谢谢,结果
罗杰

Thanks,
Roger

推荐答案

如果主要的方法的单线程的Java应用程序的的终止时,应用程序将退出code 0。如果终止需要另一个出口code,也许指示错误,你可以把

If the main method of a single threaded java application terminates, the application will terminate with exit code 0. If you need another exit code, maybe to indicate an error, you can place

System.exit(yourNumberHere);

在code(特别是境外的主要方法)的任何地方。

anywhere in the code (especially outside of the main method).

这是对多线程应用<击>,在那里你要么必须使用 System.exit 内部不同杀-9 从外面停止JVM。

This is different for multi-threaded applications , where you either have to use System.exit from the inside of kill -9 from the outside to stop the JVM.

下面是一个简单的例子,其中的主要终止不会停止应用程序(一个典型的服务或守护程序行为):

Here's a quick example where termination of main doesn't stop the application (a typical service or daemon behaviour):

public static void main(String args[]) {  
  Thread iWillSurvive = new Thread(new Runnable() {
    public void run() {
      while(true) {
        // heat the CPU
      }
    }
  });
  iWillSurvive.start();
}

注:当然,当它的run方法(或主线程的情况下,主要方法)终止线程将终止。在这种情况下,当所有线程都终止时,JVM将退出code 0(这使我们又回到最初的问题)终止。希望大家现在是幸福的。

Remark: Sure, a thread will terminate when it's run method (or the main method in case of the main thread) terminates. And in this case, when all threads have terminated, the JVM will terminate with exit code 0 (which brings us back to the initial question). Hope everybody is happy now.

这篇关于主要功能不返回任何东西。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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