守护线程

 1 package 多线程练习;
 2 
 3 /*
 4     虚拟机一定会执行完用户线程,当用户线程执行完毕 守护线程也就没了
 5     将线程设置为守护线程的方法 threadGod.setDaemon(true);  //  设置成守护线程 默认值:false 用户线程  true:守护线程
 6  */
 7 public class 守护线程 {
 8     public static void main(String[] args) {
 9 
10         // 人活的每一天 用户线程
11         Runnable humanity = () -> {
12             for (int i = 0; i < 365000; i++) {
13                 System.out.println("开心每一天");
14             }
15             System.out.println("===========goodbye world===========");
16         };
17 
18         // 信仰 守护线程
19         Runnable god = () -> {
20             while (true) {
21                 System.out.println("上帝保佑你");
22             }
23         };
24 
25         Thread threadGod = new Thread(god);
26         threadGod.setDaemon(true);  //  设置成守护线程 默认值:false 用户线程  true:守护线程
27         threadGod.start();          //  启动守护线程
28 
29         new Thread(humanity).start();
30 
31 
32     }
33 }

执行结果

原文地址:https://www.cnblogs.com/wooroc/p/15807395.html