守护线程Daemon

Every   thread   has   a   priority.   Threads   with   higher   priority   are   executed   in   preference   to   threads   with   lower   priority.   Each   thread   may   or   may   not   also   be   marked   as   a   daemon.   When   code   running   in   some   thread   creates   a   new   Thread   object,   the   new   thread   has   its   priority   initially   set   equal   to   the   priority   of   the   creating   thread,   and   is   a   daemon   thread   if   and   only   if   the   creating   thread   is   a   daemon.           上面一段是jdk文档里面对Thread的一段描述

        Daemon   thread   在Java里面的定义是,如果虚拟机中只有Daemon   thread   在运行,则虚拟机退出。     虚拟机中可能会同时有很多个线程在运行,只有当所有的非守护线程都结束的时候,虚拟机的进程才会结束,不管在运行的线程是不是   main()   线程。 

class   A   implements   runnable{  
          public   void   run(){  
                  for(;;){  
                          System.out.println("Thread   A   run");  
                  }  
          }  
   
          public   static   void   main(String[]   args){  
                  System.out.println("Thread   main   started!");  
                  try{  
                          (new   Thread(new   A())).start();  
                  }   catch   (Exception   e){  
                  }  
                  System.out.println("Thread   main   ended!");  
          }  
  };  
  会一直跑下去,因为main进程结束了,但   A   进程还没有结束,虚拟机不能退出,  
   
  class   A   implements  implements  runnable{  
          public   void   run(){  
                  for(;;){  
                          System.out.println("Thread   A   run");  
                  }  
          }  
   
          public   static   void   main(String[]   args){  
                  System.out.println("Thread   main   started!");  
                  try{  
                          Thread   a   =   new   Thread(new   A());  
                          a.setDaemon(true);  
                          a.start();  
                  }   catch(Exception   e){  
                  }  
                  System.out.println("Thread   main   ended!");  
          }  
  };  
   
  main   线程一退出,虚拟机就退出了,因为剩下在跑的   a   线程是守护线程,虚拟机不管它的死活的,直接退出了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值