多线程并发学习(二):Daemon线程

1. daemon线程即守护线程

Java 中有两种线程: 一种是用户线程(User Thread),一种是守护线程(Daemon Thread)。

守护线程是一种特殊的线程, 它的特殊有“陪伴”的含义, 当线程中不存在非守护线程时, 则守护线程自动销毁。

垃圾回收线程就是一种守护线程, 当线程中没有非守护线程了, 则垃圾回收线程就会自动销毁。

因此, 守护线程的作用就是为其他非守护线程的线程服务, 当非守护线程不存在时, 其自然就没有存在的必要了。

当一个JVM中所有非daemon线程都退出了,JVM就会退出。

2. 标志是否是daemon线程

setDaemon(boolean);必须在线程启动之前(start()方法前)进行设置。
boolean isDaemon();判断是否是守护线程

注意:守护线程中产生的线程也是守护线程;

例1:setDaemon(true)

import java.util.concurrent.TimeUnit;

public class DaemonTest {
    public static void main(String[] args) {
        Thread thread = new Thread(new DaemonRunner(),"DaemonRunner");
        thread.setDaemon(true);//start方法前
        thread.start();
    }

    static class DaemonRunner implements Runnable{
        @Override
        public void run() {
            try{
                TimeUnit.SECONDS.sleep(10);
            }catch (InterruptedException e){
                System.out.println("Setp into InterruptedException.");
            } finally {
                System.out.println("DaemonThread finally run.");
            }
        }
    }
}

分析:运行代码控制台输出为空,为何?

程序运行,main线程中启动了Daemon线程,然后main线程马上就结束了,此时JVM中已经没有非Daemon线程了,所以JVM退出了。JVM中的所有Daemon线程也都需要立即终止,即使finally块中的内容还没有打印,DaemonRunner线程也终止了。

构建Daemon线程时,不能依靠finally块中的内容确保执行关闭或者清理资源的逻辑。

例2:setDaemon(false)

public class DaemonTest {

    public static void main(String[] args) {
        WorkerThread thread = new WorkerThread();
        
        System.out.printf("work thread daemon: %b\n", thread.isDaemon());
        System.out.printf("main thread daemon: %b\n", Thread.currentThread().isDaemon());
        
        thread.start();
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("main thread exit") ;
        //System.exit(0);
    }

}

class WorkerThread extends Thread {
    public WorkerThread() {
        // if true, JVM will quit after main thread quit
        // if false, JVM will not quit, because this workerThread will never end.
        setDaemon(false);
    }

    public void run() {
        for (int i = 0; ; i++) {
            System.out.printf("work thread loop: %d\n", i);
            try {
                sleep(1 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果:JVM将不会退出了

work thread daemon: false
main thread daemon: false
work thread loop: 0
work thread loop: 1
work thread loop: 2
main thread exit
work thread loop: 3
work thread loop: 4
......

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值