创建守护线程来支持用户线程。它通常在后台工作,并在所有其他线程关闭后终止。垃圾收集器是守护线程的示例之一。
守护线程的特征
守护线程是低优先级线程。
守护程序线程是服务提供者线程,不应用作用户线程。
JVM 自动关闭守护程序如果不存在活动线程,则恢复该线程;如果用户线程再次活动,则恢复该线程。
如果所有用户线程都完成,守护线程无法阻止 JVM 退出。
示例 1
在此示例中,我们创建了一个继承 Thread 类的 ThreadDemo 类。在main方法中,我们创建了三个线程。由于我们没有将任何线程设置为守护线程,因此没有线程被标记为守护线程。
package com.yxjc123;
class ThreadDemo extends Thread {
ThreadDemo( ) {
}
public void run() {
System.out.println("Thread " + Thread.currentThread().getName()
+ ", is Daemon: " + Thread.currentThread().isDaemon());
}
public void start () {
super.start();
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo thread1 = new ThreadDemo();
ThreadDemo thread2 = new ThreadDemo();
ThreadDemo thread3 = new ThreadDemo();
thread1.start();
thread2.start();
thread3.start();
}
}
输出
Thread Thread-1, is Daemon: false
Thread Thread-0, is Daemon: false
Thread Thread-2, is Daemon: false
示例 2
在此示例中,我们创建了一个继承 Thread 类的 ThreadDemo 类。在main方法中,我们创建了三个线程。由于我们将一个线程设置为守护线程,因此一个线程将被打印为守护线程。
package com.yxjc123;
class ThreadDemo extends Thread {
ThreadDemo( ) {
}
public void run() {
System.out.println("Thread " + Thread.currentThread().getName()
+ ", is Daemon: " + Thread.currentThread().isDaemon());
}
public void start () {
super.start();
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo thread1 = new ThreadDemo();
ThreadDemo thread2 = new ThreadDemo();
ThreadDemo thread3 = new ThreadDemo();
thread3.setDaemon(true);//设为守护线程
thread1.start();
thread2.start();
thread3.start();
}
}
输出
Thread Thread-1, is Daemon: false
Thread Thread-2, is Daemon: true
Thread Thread-0, is Daemon: false
示例 3
在此示例中,我们创建了一个继承 Thread 类的 ThreadDemo 类。在main方法中,我们创建了三个线程。线程一旦启动,就不能将其设置为守护线程。由于我们在启动后将一个线程设置为守护线程,因此会引发运行时异常。
package com.yxjc123;
class ThreadDemo extends Thread {
ThreadDemo( ) {
}
public void run() {
System.out.println("Thread " + Thread.currentThread().getName()
+ ", is Daemon: " + Thread.currentThread().isDaemon());
}
public void start () {
super.start();
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo thread1 = new ThreadDemo();
ThreadDemo thread2 = new ThreadDemo();
ThreadDemo thread3 = new ThreadDemo();
thread1.start();
thread2.start();
thread3.start();
thread3.setDaemon(true);//因为所有线程已经退出,这里再设置守护线程则报错
}
}
输出
Exception in thread "main" Thread Thread-1, is Daemon: false
Thread Thread-2, is Daemon: false
Thread Thread-0, is Daemon: false
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Unknown Source)
at com.yxjc123.TestThread.main(TestThread.java:27)