Java Main線程與子線程之間的關係

參考:https://www.cnblogs.com/qiumingcheng/p/8202393.html

1、Main線程結束之後,子線程非守護線程會繼續運行 。

public class DaemonThread {
   private static class UseThread extends Thread{
      @Override
      public void run() {
         while (true) {
            System.out.println(Thread.currentThread().getName()
                  + " I am extends Thread.");
         }

      }
   }

   public static void main(String[] args) {
      UseThread useThread = new UseThread();
      //useThread.setDaemon(true);
      useThread.start();

   }
}

2、Main線程不能設置爲守護線程,子線程可以設置成守護線程。

public static void main(String[] args) {

		Thread.currentThread().setDaemon(true);

		UseThread useThread = new UseThread();
		//useThread.setDaemon(true);
		useThread.start();

	}


Exception in thread "main" java.lang.IllegalThreadStateException
	at java.lang.Thread.setDaemon(Thread.java:1359)

3、虛擬機中沒有非守護線程執行時,進程結束,即使有守護線程。

public static void main(String[] args) {

	//	Thread.currentThread().setDaemon(true);

		UseThread useThread = new UseThread();
		useThread.setDaemon(true);
		useThread.start();

	}


console : 
Process finished with exit code 0

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章