守护线程

守护线程

守护线程的例子搞的我很伤感,终有离世的一天,愿我们每天都能开心度过。

线程分为用户线程(main线程)和守护线程(gc 垃圾回收线程)

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

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

守护线程例子:后台记录操作日志、监控内存、垃圾回收等等

例子:

package com.example.multi_thread;

public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        You1 you1 = new You1();

        Thread thread = new Thread(god);
        thread.setDaemon(true);
        thread.start();

        new Thread(you1).start();

    }
}

class God implements Runnable {

    @Override
    public void run() {
        while (true) {
            System.out.println("God bless you!");
        }
    }
}

class You1 implements Runnable {

    @Override
    public void run() {
        System.out.println("Hello World!");
        for (int i = 0; i < 36500; i++) {
            System.out.println("Happy Day~");
        }
        System.out.println("Bye world!");
    }
}
posted @ 2021-11-12 16:24  Oh,mydream!  阅读(20)  评论(0编辑  收藏  举报