在Java的线程机制中,有两类线程: this
Daemon Thread的做用是为其余线程的运行提供服务,好比说GC线程。其实User Thread线程和Daemon Thread守护线程本质上来讲去没啥区别的,惟一的区别之处就在虚拟机的离开时候:若是User Thread所有撤离,那么Daemon Thread也就没啥线程好服务的了,因此虚拟机也就退出了。只要当前JVM实例中尚存在任何一个非守护线程没有结束,守护线程就所有工做;只有当最后一个非守护线程结束时,守护线程随着JVM一同结束工做。守护线程最典型的应用就是 GC (垃圾回收器)。线程
守护线程并不是只有虚拟机内部能够提供,用户也能够自行的设定守护线程,能够经过Thread的setDaemon方法来设置,这个值的默认值是false,即默认是用户线程code
class TestRunnable implements Runnable{ public void run(){ try{ Thread.sleep(1000);//守护线程阻塞1秒后运行 System.out.println("this thread is running"); catch(IOException e){ e.printStackTrace(); } } } public class TestDemo{ public static void main(String[] args) throws InterruptedException { Runnable tr=new TestRunnable(); Thread thread=new Thread(tr); thread.setDaemon(true); //设置守护线程 thread.start(); //开始执行分进程 System.out.println("main thread is finished"); } }
运行结果:只输出了“main thread is finished” 由于设置了thread.setDaemon(true); 当没有正在执行的用户线程的时候,守护线程也会结束。进程
若是把thread.setDaemon(true); 注释掉,会同时输出:"main thread is finished"和"this thread is running"虚拟机