Java中线程分为两类:用户线程和守护线程
守护线程为陪伴线程,只要JVM中存在有任何一个用户线程没有终止,守护线程就一直在工作。
默认创建的线程都是用户线程,主线程也是用户线程。
通过setDaemon(true)将线程对象设置为守护线程。
Java中典型的守护线程,垃圾回收线程,JVM启动,他就启动,JVM终止,他就结束
从这段代码的执行过程可以看到,等待用户线程运行结束,守护线程就结束。
区别线程是不是守护线程用isDaemon()方法
public class DaemonThread {
public static void main(String[] args) {
Runnable runnable = new DaemonTest();
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.setDaemon(true);
thread1.start();
thread2.start();
try {
Thread.sleep(2000);
thread2.interrupt();
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("代码结束。。。");
}
}
class DaemonTest implements Runnable{
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName()+ " "+Thread.currentThread().isDaemon() +" try");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName()+" "+Thread.currentThread().isDaemon()+" catch");
e.printStackTrace();
return;
}
}
}
}