java线程分为守护线程和非守护线程,当java jvm检测主线程或其他子线程执行完之后,守护线程也会马上停止执行,我们可以使用Thread.setDaemon(ture或false)来设置一个线程是守护线程还是非守护线程,默认为false,可以通过Thread.isDaemon()方法查询该线程是否是守护线程
1:我们将用案例来告诉你守护线程和非守护线程的区别和用法,代码如下,先设置其为守护线程。
package com.baidu; public class DeamonThread { public static void main(String[] args) { //"DeamonThread::print"是java1.8调用静态方法 Thread thread = new Thread(DeamonThread::print); thread.setDaemon(true); thread.start(); System.out.println("退出Main方法"); } public static void print() { int counter = 1; while (true) { try { System.out.println("Counter:" + counter++); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
print()方法里面是一个while死循环,以上代码输出结果如下,只输出一次便退出了while(true)循环。
退出Main方法 Counter:1:
2:如果我们将daemon设置为非守护线程,代码如下。
thread.setDaemon(false);
这时候就不会退出while(true)循环了,会一直执行下去,结果如下:
退出Main方法 Counter:1 Counter:2 Counter:3 .......
总结:非守护线程其实就是守护线程的氧气,如果氧气没了,守护线程也会跟着死掉。