天天看点

主线程、子线程、守护线程

  1. import static java.util.concurrent.TimeUnit.*;     
  2. public class DaemonTest {     
  3.     public static void main(String[] args) throws InterruptedException {     
  4.         Runnable r = new Runnable() {     
  5.             public void run() {     
  6.                 for (int time = 10; time > 0; --time) {     
  7.                     System.out.println("Time #" + time);     
  8.                     try {     
  9.                         SECONDS.sleep(2);     
  10.                     } catch (InterruptedException e) {     
  11.                         e.printStackTrace();     
  12.                     }     
  13.                 }     
  14.             }     
  15.         };     
  16.         Thread t = new Thread(r);     
  17.         t.setDaemon(true);  // try to set this to "false" and see what happens     
  18.         t.start();     
  19.         System.out.println("Main thread waiting...");     
  20.         SECONDS.sleep(6);     
  21.         System.out.println("Main thread exited.");     
  22.     }     

当t.setDaemon(true),即t为Daemon线程时,执行结果如下:

t为Daemon线程的输出: 

Time #10

Time #9

Time #8

Main thread exited.

Time #7

当t.setDaemon(false),即t为非守护线程时,执行结果如下:

Main thread waiting...

Time #10

Time #9

Time #8

Main thread exited.

Time #7

Time #6

Time #5

Time #4

Time #3

Time #2

Time #1

总结:  1、当主线程一结束、(非守护线程的)子线程不会立即结束。 2、当主线程一结束,(守护线程的)子线程会立即结束。 3、子线程对象,在调用start()方法之前,通过调用setDaemon(true),将本子线程设置为守护线程。