---
title: "守护线程"
author: "caowei3047"
date: "2012-10-10T11:33:33Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-10-10T11:33:53Z"
id: 1694955
url: "https://caowei3047.iteye.com/blog/1694955"
---

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   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   线程是守护线程，虚拟机不管它的死活的，直接退出了。