守护进程线程只是从属于创建它的线程的后台线程,因此当创建守护进程线程的线程结束时,守护进程线程也随之消亡。不是守护进程线程的线程称为用户线程。要创建守护进程线程,请在线程启动之前调用setDaemon()方法,并使用一个布尔值 true 作为参数。
package org.nhooo.example.lang;
public class DaemonThread implements Runnable {
private String threadName;
private DaemonThread(String threadName) {
this.threadName = threadName;
}
public void run() {
System.out.println("Running [" + threadName + "]");
}
public static void main(String[] args) {
Thread t1 = new Thread(new DaemonThread("FirstThread"));
Thread t2 = new Thread(new DaemonThread("SecondThread"));
// t1作为守护程序线程
t1.setDaemon(true);
t1.start();
// t2是用户线程
t2.start();
}
}