main()中System.exit()的作用

转载注明出处,谢谢。http://www.cnblogs.com/wdfwolf3/

  main()主函数再熟悉不过,了解java的人也都知道System.exit()方法是停止虚拟机运行。那这里为什么还要单独写一篇博客,都是源于朋友发的一张最近刚买的T恤照片,就是上面这张图。这是一个经典的helloworld程序,吸引我的是主函数中最后那句"System.exit(0);",主函数运行结束自然会停止执行机使整个程序退出,那加上一句是否还有必要,有什么区别。这里查阅一下论坛发现有些说法也不够准确,网上随处可见的两条常规结论如下,

1.如果是普通方法(非程序入口,即主函数),那么方法结束是返回到调用位置,程序继续执行;System.exit(0)是停止执行机,将程序停掉。

2.在主函数中,没有区别,加不加都是程序结束。

  第一条容易理解,第二条为什么不准确,因为还有这种情况,如下代码,大家看到后应该会恍然大悟我要说明的问题,即主函数启动了一个线程,那么正常情况下主函数会等待线程结束然后结束程序。这里的System.exit(0);加与不加就体现出区别了,加了之后不等待线程执行完,main函数运行到这一句直接将虚拟机停止,程序结束。所以第二条说没有区别并不准确。

public class MainWaitThread {
    public static void main(String[] args) {
        System.out.println("Hello world");
        Thread thread =  new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread start!");
                long l = System.currentTimeMillis();
                while (System.currentTimeMillis() - l < 10000);
                System.out.println("Thread stop!");
            }
        });
        thread.start();
        System.exit(0);
    }
}

  最后说一下System.exit()这个方法,接收一个参数status,0表示正常退出,非零参数表示非正常退出。不管status为何值都会退出程序。和return 相比,return是回到上一层,而System.exit(status)是回到最上层。

 /**
     * Terminates the currently running Java Virtual Machine. The
     * argument serves as a status code; by convention, a nonzero status
     * code indicates abnormal termination.
     * This method calls the <code>exit</code> method in class
     * <code>Runtime</code>. This method never returns normally.
     * The call <code>System.exit(n)</code> is effectively equivalent to
     * the call:
     * @param      status   exit status.
     * @throws  SecurityException
     *        if a security manager exists and its <code>checkExit</code>
     *        method doesn't allow exit with the specified status.*/
    public static void exit(int status) {
        Runtime.getRuntime().exit(status);
    }

 

posted @ 2017-09-02 15:12  wdfwolf3  阅读(20224)  评论(0编辑  收藏  举报