守护线程是为用户线程提供服务的低优先级后台线程。它的生命取决于用户线程。如果没有用户线程正在运行,那么即使守护线程正在运行,JVM 也可以退出。JVM 不等待守护线程完成。
守护线程执行后台任务,例如垃圾收集、终结器等。
守护线程的唯一目的是为用户线程服务,所以如果没有用户线程,JVM 就没有必要运行这些线程,这就是为什么一旦没有用户线程,JVM 就会退出。
与守护线程相关的两种方法
Public void setDaemon(boolean status) : 此方法可用于将线程标记为用户或守护线程。如果你把 setDaemon(true),它使线程作为守护进程。
public boolean isDaemon() 这个方法可以用来检查线程是否是守护进程。
守护线程示例:
package org.arpit.java2blog;
class SimpleThread 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 DaemonThreadMain {
public static void main(String[] args){
SimpleThread st=new SimpleThread();
Thread th1=new Thread(st,"Thread 1");//creating threads
Thread th2=new Thread(st,"Thread 2");
Thread th3=new Thread(st,"Thread 3");
th2.setDaemon(true);//now th2 is daemon thread
th1.start();//starting all threads
th2.start();
th3.start();
}
}
当你运行上面的程序时,你会得到下面的输出:
Thread 1 is user thread
Thread 3 is user thread
Thread 2 is daemon thread
请注意,一旦启动,就不能将用户线程转换为守护线程,否则会抛出IllegalThreadStateException。
package org.arpit.java2blog;
class SimpleThread 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 DaemonThreadMain {
public static void main(String[] args){
SimpleThread st=new SimpleThread();
Thread th1=new Thread(st,"Thread 1");//creating threads
Thread th2=new Thread(st,"Thread 2");
Thread th3=new Thread(st,"Thread 3");
th1.start();//starting all threads
th2.start();
th3.start();
th2.setDaemon(true);//now converting user thread to daemon thread after starting the thread.
}
}
当你运行上面的程序时,你会得到下面的输出:
Thread 1 is user threadException in thread “main”
Thread 2 is user thread
Thread 3 is user thread
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Thread.java:1388)
at org.arpit.java2blog.DaemonThreadMain.main(DaemonThreadMain.java:28)
|