欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

daemon线程和user线程的区别

程序员文章站 2022-03-24 11:07:41
...

java中的线程分为两大类:daemon和User线程。

默认创建的都是user线程。

当进程中不存在任何User线程时jvm就会退出。

比如

public class TestRxJava {

    private static final String THREAD_NUM="sub-thread";

    public static void main(String[] args) {
        System.out.println("--"+Thread.currentThread().getName()+"-----");

       Thread thread =new Thread(new Runnable(){


               public void run(){


               try{
                   Thread.sleep(2000);

                   System.out.println("--"+Thread.currentThread().getName()+"-----");
                }
               catch(InterruptedException e){
                   e.printStackTrace();
               }
           }
       },THREAD_NUM);

        //thread.setDaemon(true);
        thread.start();




    }


}

 这个是user进程 一定会等sub-thread打印完才结束,如果设置thread.setDaemon(true);则main打印完jvm就结束了,sub-thread没机会打印了。