守护线程Daemon
-
线程分为用户线程和守护线程。
-
虚拟机必须确保用户线程执行完毕。
-
虚拟机不用等待守护线程执行完毕。
-
如:后台记录操作日志,监控内存,垃圾回收等。
-
使用setDaemon(boolean b)设置守护线程,正常线程都是用户线程(默认false)
代码示例
package com.thread;
//守护线程
public class TestDaemon {
public static void main(String[] args) {
Human human = new Human();
God god = new God();
Thread t1 = new Thread(god);
t1.setDaemon(true);//默认false 表示是用户线程 正常线程都是用户线程
t1.start();//god线程启动
new Thread(human).start();//human 用户线程启动
}
}
class Human implements Runnable{
@Override
public void run() {
for (int i = 0; i < 3650; i++) {
System.out.println("happy this"+ i);
}
System.out.println("dead?");
}
}
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝守护着你!");
}
}
}