守护程序线程是java中的一个低优先级线程,它在后台运行,并且主要由JVM创建,用于执行后台任务,例如垃圾回收(GC)。 如果没有用户线程在运行,那么即使守护程序线程在运行,JVM也可以退出。守护程序线程的唯一目的是服务用户线程。的isDaemon()方法可用于确定线程是守护线程或没有。
Public boolean isDaemon()
class SampleThread implements Runnable {
public void run() {
if(Thread.currentThread().isDaemon())
System.out.println(Thread.currentThread().getName()+" is daemon thread");
else
System.out.println(Thread.currentThread().getName()+" is user thread");
}
}
//主类
public class DaemonThreadTest {
public static void main(String[] args){
SampleThread st = new SampleThread();
Thread th1 = new Thread(st,"Thread 1");
Thread th2 = new Thread(st,"Thread 2");
th2.setDaemon(true); // set the thread th2 to daemon.
th1.start();
th2.start();
}
}输出结果
Thread 1 is user thread Thread 2 is daemon thread