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线程.
5.默认产生的线程全部是Non-daemon线程.
- 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!"); -
} -
};
- 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!"); -
} -
};