用户线程:主线程的子线程,当主线程结束时,用户线程也会结束。
守护线程:一种特殊的线程,它是在后台运行的,当所有用户线程结束时,守护线程也会随之结束。例如gc线程
public class ThreadDemo { public static void main(String[] args) { Thread userThread = new Thread(new Runnable() { public void run() { try { Thread.sleep(5000); System.out.println("用户线程执行完毕"); } catch (InterruptedException e) { e.printStackTrace(); } } }); userThread.start(); Thread daemonThread = new Thread(new Runnable() { public void run() { while (true) { System.out.println("守护线程正在运行"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); daemonThread.setDaemon(true); daemonThread.start(); System.out.println("主线程执行完毕"); } }
输出结果:
结论:主线程结束,用户线程仍在执行,守护线程也在执行,当用户线程结束,守护线程一同结束。
标签:Thread,用户,线程,new,public,守护 From: https://www.cnblogs.com/katsu2017/p/17241100.html