- 当线程设置为守护线程时,其线程的父线程结束时,其线程也结束。如:程序开启一个守护线程向服务器发送心跳,当程序结束时,这个守护线程同样结束
package com.cfl.thread;
public class Thread4 {
public static void main(String[] args) throws Exception {
// 创建测试线程
Thread thread = new Thread(new Runnable() {
public void run() {
for(int i = 0; i < 15; i++) {
if(i == 5) {
// 创建守护线程
System.out.println(Thread.currentThread().getName() + " 开启一个守护线程");
Thread daemonThread = new Thread(new Runnable() {
public void run() {
while (true) {
try {
System.out.println(Thread.currentThread().getName() + " 发送心跳...");
Thread.sleep(1*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"daemonThread");
// 设置为守护进程
daemonThread.setDaemon(true);
daemonThread.start();
}
try {
System.out.println(Thread.currentThread().getName() + " 测试程序执行过程:" + i);
Thread.sleep(1*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"testThread");
thread.start();
}
}