守护线程实战与应用场景
守护线程
-
程序分为用户线程和守护线程 虚拟机不会等待守护线程执行完毕
守护线程一般用来做一些 “不关键的事情”
如gc垃圾回收器就是一个经典的守护线程
package com.li.changGe.multithreading.threadState;
public class DaemonDemo01 {
public static void main(String[] args) {
/**
* 播放器线程始终守护着视频线程
*
* player.setDaemon(true);
* 设置播放器线程为守护线程
*/
Thread player = new Thread(() -> {
System.out.println("播放器打开了");
while (true){
System.out.println("播放器进行中");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//while
});
Thread video = new Thread(() -> {
System.out.println("视频打开了");
for (int i = 0; i < 3; i++) {
System.out.println("看视频中");
}
System.out.println("视频关闭了");
});
/**
* 默认为false用户线程
*/
player.setDaemon(true);
player.start();
video.start();
}
}
