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

  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.              
  17.         Thread t = new Thread(r);     
  18.         t.setDaemon(true);  // try to set this to "false" and see what happens     
  19.         t.start();     
  20.              
  21.         System.out.println("Main thread waiting...");     
  22.         SECONDS.sleep(6);     
  23.         System.out.println("Main thread exited.");     
  24.     }     


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),将本子线程设置为守护线程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值