守护线程和用户线程的区别
守护线程: 为程序提供后端服务的线程成为守护线程,非守护线程运行结束时守护线程也一并结束;
用户线程:用户线程和守护线程唯一的区别就是Daemon(Thread.getDaemon())为false;
import static java.lang.Thread.currentThread;
public class CreateRunnable implements Runnable {
@Override
public void run() {
for(int i = 0; i < 30; i++) {
System.out.println(currentThread().getName()+" "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类:
public class ThreadTest {
public static void main(String[] args) {
CreateRunnable createRunnable = new CreateRunnable();
Thread thread1 = new Thread(createRunnable);
thread1.setDaemon(true); // 守护线程,和主线程一起销毁
thread1.start();
for(int i = 0; i < 30; i++) {
System.out.println(Thread.currentThread().getName()+" "+i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("===主线程结束===");
}
}
输出结果: