守护(daemon)线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕 如gc线程
- 如,后台记录操作日志,监控内存,垃圾回收等待..
- 设置为守护线程核心就是将线程的setDaemon(true)设置为true
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
Person person = new Person();
Thread thGod = new Thread(god);
thGod.setDaemon(true);//将上帝设置为守护线程,默认为false,正常的线程都是用户线程
//开启守护线程
thGod.start();
new Thread(person).start();
}
}
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("God blesses you!");
}
}
}
class Person implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("活着很开心!");
}
System.out.println("see you!");
}
}