守护线程

线程分为 用户线程 和 守护线程
虚拟机必须确保用户线程执行完毕
虚拟机不用等待守护线程执行完毕
如,后台记录操作日志,监控内存,垃圾回收等待...

package com.qiliang.demo12_线程守护;
// 测试守护线程
// 上帝守护着你
public class DaemonTest {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        // 默认值是false表示是用户线程,正常的线程都是用户线程
        // 除非加了.setDaemon 就是守护线程
        thread.setDaemon(true);
        thread.start(); // 启动上帝守护线程

        new Thread(you).start(); // You 用户线程启动
    }
}


// 上帝
class God implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("上帝一直在保佑着你");
        }
    }
}


// 你
class You implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 365; i++) {
            System.out.println("一年开心的活着了"+i+"天");
        }
        System.out.println("goodbye!world!");
    }
}
posted @ 2020-04-28 17:38  阿亮在努力  阅读(92)  评论(0)    收藏  举报