Thread类创建出来的线程默认都是前台线程。调用Thread类的setDaemon(true)可将当前线程设置为守护线程(也称为后台线程)。
守护线程是用来守护前台线程的,只要进程中有前台线程存活,守护线程一直守护,直到进程中所有前台线程结束,进程结束,守护线程强制结束。
gc是一个守护线程,只要堆里有对象,gc一直活着。
设rose为前台线程,jack为守护线程,rose落水,jack不再呼喊。
public class DaemonDemo {
public static void main(String[] args) {
//创建rose前台线程
Thread rose =new Thread("rose"){
public void run() {
for(int i=0;i<5;i++ ){
System.out.println("Jack,help me!!!");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
System.out.println("Rose drowned !!!");
};
};
//创建jack后台线程
Thread jack=new Thread("jack")
{
public void run() {
while(true){
System.out.println("You jump,I jump!!!");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
};
jack.setDaemon(true);
System.out.println(jack.getName()+" is Daemon ? "+jack.isDaemon());
System.out.println(rose.getName()+" is Daemon ? "+rose.isDaemon());
rose.start();
jack.start();
}
}
运行结果
jack is Daemon ? true
rose is Daemon ? false
Jack,help me!!!
You jump,I jump!!!
You jump,I jump!!!
Jack,help me!!!
You jump,I jump!!!
Jack,help me!!!
You jump,I jump!!!
Jack,help me!!!
You jump,I jump!!!
Jack,help me!!!
You jump,I jump!!!
Rose drowned !!!