Java - 守护线程
Java 中的守护线程
守护线程(Daemon thread)用于支持用户线程。它通常在后台运行,一旦所有其他线程关闭,它就会终止。垃圾回收器(Garbage collector)就是守护线程的一个例子。
Java 中守护线程的特性
守护线程是低优先级线程。
守护线程是服务提供线程,不应作为用户线程使用。
如果没有活动线程存在,JVM 会自动关闭守护线程;如果用户线程再次活跃,JVM 会重新启动它。
如果所有用户线程都已完成,守护线程无法阻止 JVM 退出。
Java 守护线程的 Thread 类方法
以下是 Thread 类为 Java 中的守护线程提供的方法:
Thread.setDaemon() 方法:将此线程标记为守护线程或用户线程。
Thread.isDaemon() 方法:检查此线程是否为守护线程。
Java 守护线程示例
在这个示例中,我们创建了一个继承 Thread 类的 ThreadDemo 类。在 main 方法中,我们创建了三个线程。由于我们没有将任何线程设置为守护线程,因此没有线程被标记为守护线程。
package com.;
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
Java 守护线程的更多示例
示例 1
在这个示例中,我们创建了一个继承 Thread 类的 ThreadDemo 类。在 main 方法中,我们创建了三个线程。由于我们将一个线程设置为守护线程,因此将有一个线程被打印为守护线程。
package com.;
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
示例 2
在这个示例中,我们创建了一个继承 Thread 类的 ThreadDemo 类。在 main 方法中,我们创建了三个线程。一旦线程启动,就不能再将其设置为守护线程。由于我们在线程启动后设置一个线程为守护线程,将引发运行时异常。
package com.;
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..TestThread.main(TestThread.java:27)