线程分为用户线程和守护线程
- 用户线程:虚拟机必须确保用户线程执行完毕
- 守护线程:虚拟机不需要等待守护线程执行完毕
package StateThread;
// 测试守护线程
public class TestDaemon {
public static void main(String[] args) {
You you = new You();
God god = new God();
Thread t1 = new Thread(god);
t1.setDaemon(true); // 将线程t1设置为守护线程,默认为false表示用户线程,正常的线程都是用户线程
t1.start(); // 守护启动线程t1
new Thread(you).start(); // 用户启动线程you
}
}
// 你类,实现了Runnable接口
class You implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("你开心的活着"); // 输出信息
}
System.out.println("====你的生命结束====="); // 输出分隔线
}
}
// 神类,实现了Runnable接口
class God implements Runnable {
@Override
public void run() {
while (true){
System.out.println("神在保护着你"); // 输出信息
}
}
}
![image]()