005 守护线程

一 .概述

  在前面我们说到过守护线程的特点,就是守护线程的存在必须要有一个非守护线程的存在.

  利用这个特性,我们常常使用守护线程做垃圾回收,心跳检测的后台的服务.

  本节,我们利用守护线程实现一个线程终结的方法.


二 .利用守护线程的特性,实现线程的终结

    public static void main(String[] args) throws InterruptedException {
        
        // 创建一个守护线程
        Thread t = new Thread(()->{
            for(;;)
                System.out.println(" Daemon Thread is running ...");
        });
        t.setDaemon(true);
        
        t.start();
        
        //让主线程休眠3秒,此时守护线程的生命周期依赖于主线程
        TimeUnit.SECONDS.sleep(3);
        
    }

我们运行上面的代码,主线程在休眠3秒之后终结,此时守护线程由于其特性就会终结自己的生命周期.


三 . 守护线程实现心跳检测的示例

public static void main(String[] args) {
        System.out.println("主程序开始运行");
        //开启守护线程作为心跳检测
        check();
        
        //主线程运行100次之后终结自己,此时,守护线程也就没有必要存在了
        IntStream.range(1, 100).forEach((e)->{
            System.out.println("主程序在运行当中.....");
        });
        
        // 主线程终结
        System.out.println("main thread is endding...");
        
    }
    
    public static void check() {
        Thread t = new Thread(()->{
            for(;;)
                System.out.println(" Daemon Thread is checking ...");
        });
        t.setDaemon(true);
        // 设置低优先级
        t.setPriority(Thread.MIN_PRIORITY);
        t.start();
    }