> 文档中心 > 「淘宝二面」什么是守护线程 应用场景有哪些

「淘宝二面」什么是守护线程 应用场景有哪些

什么是守护线程

jdk官方介绍

The Java Virtual Machine exits when the only threads running are all daemon threads.

当 JVM 中不存在任何一个正在运行的非守护线程时,则 JVM 进程即会退出

先看一下这段代码

public static void main(String[] args) throws InterruptedException {Thread t1 = new Thread(() -> {while (true) {try {Thread.sleep(1000);System.out.println("running ...");} catch (InterruptedException e) {e.printStackTrace();}}});t1.start();Thread.sleep(1000);System.out.println("主线程退出");}

运行程序 

由结果可以看出,当主线程退出时,子线程并不会退出,因为其非守护线程正在运行时JVM并不会退出。

给线程设置为守护线程

public static void main(String[] args) throws InterruptedException {Thread t1 = new Thread(() -> {while (true) {try {Thread.sleep(1000);System.out.println("running ...");} catch (InterruptedException e) {e.printStackTrace();}}});// 设置守护线程t1.setDaemon(true);t1.start();Thread.sleep(2000);System.out.println("主线程退出");}

运行程序

 当主线程退出后,JVM也随之退出。

应用场景

JVM中的垃圾回收线程算是比较典型的守护线程了,当JVM退出后,其垃圾回收线程也会随之关闭。

笑话娱乐网站