守护线程是一种特殊的线程,是一种陪伴线程。
1. java线程分类
用户线程
例如自己创建的线程。
守护线程
垃圾回收机制等。
2. 区分
可以通过isDaemon()方法来区别它们:如果返回false,则说明该线程是“用户线程”;否则就是“守护线程”。
class MyThread implements Runnable {
@Override
public void run() {
System.out.println("创建线程");
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new MyThread());
thread.start();
System.out.println(thread.isDaemon());
}
}
运行结果:
只要当前JVM进程中存在任何一个非守护线程没有结束,守护线程就在工作;只有当最后一个非守护线程结束时,守护线程才会随着JVM一同停止工作。
主线程main也是用户线程。
public class Test12 {
public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().isDaemon());
}
}
运行结果: