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
发布了39 篇原创文章 · 获赞 1 · 访问量 8783

猜你喜欢

转载自blog.csdn.net/oDengTao/article/details/103341014