線程分為用戶線程和守護線程,如果代碼中不特殊設(shè)置一般都為用戶線程渣蜗。
虛擬機必須確保用戶線程執(zhí)行完畢
虛擬機不必等待守護線程執(zhí)行完畢
一般用在監(jiān)控記錄等需求中
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("老師在監(jiān)考");
} 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("學(xué)生在考試:完成第" + i + "題");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("考試完成屠尊!");
}
}