天天看點

主線程、子線程、守護線程

  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),将本子線程設定為守護線程。