System.exit和Runtime halt區別

來源:互聯網
上載者:User

標籤:

看到RM在處理異常的時候使用了兩種退出方式,而且是針對不同的異常。特意查詢了一些資料來看看,兩種方式有什麼不同。

System.exit

終止當前正在啟動並執行Java虛擬機器。參數作為狀態碼,按照慣例,一個非零狀態代碼表示異常終止。

用線程描述,在多線程情況下,可能更準確一些

1.調用方法後,線程會退出

2.未捕獲的異常被線程拋出,但如果有其他非守護線程,程式將繼續運行。

3.反饋狀態代碼,一般在指令碼中有用。

4.線程退出,還是做一些清理動作

------------------------------------------------------------------------------------

Java虛擬機器退出包括兩個階段:

第一個階段:會以某種未指定的順序啟動所有登入鉤子,並且允許它們同時運行直至結束

第二個階段:如果已啟用runFinalizersOnExit設定為true,則運行所有未調用的終結方法(finalizer方法)

------------------------------------------------------------------------------------

Runtime.getRuntime().halt(status)

現在runtime的halt比較好理解了,他不會執行鉤子函數和finalizer方法,而是直接退出。

+++++++++++++

詳細英文解析,可以看JDK源碼或是Javadoc

+++++++++++++以下是自己寫的一個Demo,以作驗證+++++++++++++

/**
*    @author yanbit
* @date Aug 18, 2015 3:02:01 PM
*
*/
public class SystemExitAndRuntimeHaltDemo {
  public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
      Thread t = new Thread(new Hook());
      Runtime.getRuntime().addShutdownHook(t);
    }
    //System.exit(1);
    //Runtime.getRuntime().halt(-1);
  }
}

class Hook implements Runnable{
  @Override
  public void run() {
    System.out.println(Thread.currentThread().getName());
    try {
      Thread.sleep(1000);
      System.out.println(Thread.currentThread().getName()+" hook...");
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

System.exit和Runtime halt區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.