7、守护线程

线程分为用户线程和守护线程,如果代码中不特殊设置一般都为用户线程。
虚拟机必须确保用户线程执行完毕
虚拟机不必等待守护线程执行完毕
一般用在监控记录等需求中


package com.example.demo.thread;

/**
 * @projectName: demo
 * @package: com.example.demo.thread
 * @className: TestDeamon
 * @author:
 * @description: 测试守护线程
 * @date: 2021/12/7 22:17
 */
public class TestDeamon {
    public static void main(String[] args) {
        Teacher teacher = new Teacher();
        Student student = new Student();

        Thread threadT = new Thread(teacher);
        threadT.setDaemon(true);
        threadT.start();

        new Thread(student).start();
    }

}

class Teacher implements Runnable {

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(500);
                System.out.println("老师在监考");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Student implements Runnable {

    @Override
    public void run() {
        for (int i = 1; i < 5; i++) {
            try {
                Thread.sleep(1000);
                System.out.println("学生在考试:完成第" + i + "题");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("考试完成!");
    }
}
image.png

你可能感兴趣的:(7、守护线程)