1.所谓守护线程就是运行在程序后台的线程,程序的主线程Main(比方java程序一开始启动时创建的那个线程)不会是守护线程.
2.Daemon thread在Java里面的定义是,如果虚拟机中只有Daemon thread 在运行,则虚拟机退出。
3.Main主线程结束了(Non-daemon thread),如果此时正在运行的其他threads是daemon threads,JVM会使得这个threads停止,JVM也停下.
4.总之,必须等所有的Non-daemon线程都运行结束了,只剩下daemon的时候,JVM才会停下来,注意Main主程序是Non-daemon线程.
简单例子
/**
* 守护进程
* @author xing
*
*/
public class A implements Runnable{
public void run()
{
for(;;){
System.out.println("hello world");
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Thread thread = new Thread(new A());
//thread.setDaemon(true); //设置为守护进程
thread.start();
Thread.sleep(3000);
}
}