当运行的线程都为daemon线程时,JVM虚拟机则会退出

    1. public class DaemonThread {
    2. public static void main(String[] args) throws InterruptedException {
    3. Runnable task = () -> {
    4. try {
    5. Thread.sleep(1000);
    6. } catch (InterruptedException e) {
    7. e.printStackTrace();
    8. }
    9. Thread t = Thread.currentThread();
    10. System.out.println("当前线程:" + t.getName());
    11. };
    12. Thread thread = new Thread(task);
    13. thread.setName("test-thread-1");
    14. thread.setDaemon(true);
    15. thread.start();
    16. //Thread.sleep(2000);
    17. }
    18. }
    19. 输出结果:
    20. 1、当thread设置为守护线程,则有可能控制台什么也不输出(main线程先执行完)
    21. 2、否则,JVM会等待thread线程执行完