多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Daemon线程的创建以及使用场景分析 首先我们先创建一个普通的线程,我们知道main方法实际也是个线程,让他们交替打印文字: ```java /** * @program: ThreadDemo * @description: 守护线程demo * @author: hs96.cn@Gmail.com * @create: 2020-08-28 */ public class DaemonThread { public static void main(String[] args) throws InterruptedException { Thread t = new Thread() { @Override public void run() { try { System.out.println(Thread.currentThread().getName() + " running"); Thread.sleep(3_000); System.out.println(Thread.currentThread().getName() + " done"); } catch (InterruptedException e) { e.printStackTrace(); } } }; t.start(); System.out.println(Thread.currentThread().getName()); } } ``` 执行效果如下: ![](https://img.kancloud.cn/b3/27/b3271adb7ee0f9c31f750aa9b5c27864_960x638.gif) 接下来把Thread t 设置为守护线程: ```java /** * @program: ThreadDemo * @description: 守护线程demo * @author: hs96.cn@Gmail.com * @create: 2020-08-28 */ public class DaemonThread { public static void main(String[] args) throws InterruptedException { Thread t = new Thread() { @Override public void run() { try { System.out.println(Thread.currentThread().getName() + " running"); Thread.sleep(5_000); System.out.println(Thread.currentThread().getName() + " done"); } catch (InterruptedException e) { e.printStackTrace(); } } }; t.setDaemon(true); t.start(); Thread.sleep(3_000); System.out.println(Thread.currentThread().getName()); } } ``` 执行效果如下: ![](https://img.kancloud.cn/59/bc/59bc477e103a354c9fb5457878f1e308_960x638.gif) 见这时当main线程一结束,我们的t线程就退出了,因为没打印Thread-0 done。其实守护线程的使用场景还是有很多的,比如:当客户端与服务器端建立一个TCP的长链接,然后当连接建立之后就创建一个线程来给服务器发送心跳包以便服务器能监听客户端的网络状态,这时如果连接断开了那这个心跳线程也得跟着断开,接下来用代码模拟一下这个操作: ```java /** * @program: ThreadDemo * @description: 模拟客户端与服务器端建立一个TCP的长链接发送心跳包 * @author: hs96.cn@Gmail.com * @create: 2020-08-28 */ public class DaemonThread2 { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(() -> { System.out.println("tcp connection..."); Thread innerThread = new Thread(() -> { try { while (true) { System.out.println("packet sending..."); Thread.sleep(1_000); } } catch (InterruptedException e) { e.printStackTrace(); } }, "innerThread"); innerThread.setDaemon(true); innerThread.start(); try { Thread.sleep(4_000); System.out.println("tcp Disconnect..."); } catch (InterruptedException e) { e.printStackTrace(); } }, "thread"); thread.start(); } } ``` 运行效果如下: ![](https://img.kancloud.cn/1e/fe/1efe3f839d6382022e2816e7a8aaae04_960x638.gif) 可以看到:我们将发送心跳包的线程设置为守护线程,这个线程随着tcp连接的线程关闭而关闭了。 有一点值得一提:**setDaemon 必须放在start前**。