1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| public class Test { public static void main(String[] args) { Thread daemon = new Thread(() -> { while (true) { try { System.out.println("守护线程" + Thread.currentThread().getName() + "心跳"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); // 将该线程设置为守护线程 daemon.setDaemon(true); daemon.start(); Thread thread = new Thread(() -> { while (true) { try { System.out.println("用户线程" + Thread.currentThread().getName() + "心跳"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); thread.start(); try { Thread.sleep(3000); System.out.println("主线程" + Thread.currentThread().getName() + "退出!"); } catch (InterruptedException e) { e.printStackTrace(); } } }
out: 守护线程Thread-0心跳 用户线程Thread-1心跳 守护线程Thread-0心跳 用户线程Thread-1心跳 守护线程Thread-0心跳 用户线程Thread-1心跳 主线程main退出! 守护线程Thread-0心跳 用户线程Thread-1心跳 守护线程Thread-0心跳 用户线程Thread-1心跳
conclusion: 主线程退出后,守护线程依然在运行!由此得到只要任何非守护线程还在运行,守护线程就不会终止
|