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);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM