多线程--->守护线程

守护线程

1、线程分为守护线程和用户线程

2、虚拟机必须确保用户线程执行完毕

3、虚拟机不用等待守护线程执行完毕

例如: 监控内存、垃圾回收

/**
 * 测试守护线程
 */
public class TestDemon {

    public static void main(String[] args) {

        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        thread.setDaemon(true);     //默认是false表示是用户线程, 正常的线程都是用户线程、

        thread.start();     //世界    守护线程启动

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

//世界

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 < 36500; i++) {
            System.out.println("你一生都在开心的活着");
        }
        System.out.println("=====-->Goodbbye! word! --<======");    //hello word
    }
}

猜你喜欢

转载自blog.csdn.net/m0_59133441/article/details/119986680