Java中线程分为用户线程(user thread)和守护线程(daemon
thread),它们通过Thread的daemon属性标识:true表示守护线程,false表示用户线程。

  一个Thread初始默认为用户线程(daemon默认为false),创建Thread的时候默认从当前线程"继承"daemon属性,见Thread.init方法:
Thread parent = currentThread(); this.daemon = parent.isDaemon();

  当虚拟机中剩余运行的都是守护线程时,JVM会退出;只要存在至少一个用户线程,JVM就不会退出。可以在Thread.start之前调用Thread.setDaemon方法设置线程属性(用户线程/守护线程)。

  只能在Thread未开始运行之前设置daemon属性,如果Thread已经开始运行,再设置daemon会抛出IllegalThreadStateException异常,见Thread.setDaemon方法:
public final void setDaemon(boolean on) { checkAccess(); if (isAlive()) { throw
new IllegalThreadStateException(); } daemon = on; }
  例1:thread是用户线程,主线程结束后,thread会继续运行
public static void main(String[] args) throws Exception { Thread thread = new
Thread(new Runnable() { @Override public void run() { while (true) { try {
Thread.sleep(1000L); System.out.println("still running."); } catch (
InterruptedException e) { e.printStackTrace(); } } } }); //设置线程为用户线程 thread.
setDaemon(false); thread.start(); Thread.sleep(3000L); System.out.println(
"主线程退出"); } //输出 still running. still running. 主线程退出 still running. still
running. still running. still running.
  例2:thread是守护线程,主线程结束后,thread会随即停止
public static void main(String[] args) throws Exception { Thread thread = new
Thread(new Runnable() { @Override public void run() { while (true) { try {
Thread.sleep(1000L); System.out.println("still running."); } catch (
InterruptedException e) { e.printStackTrace(); } } } }); //设置线程为守护线程 thread.
setDaemon(true); thread.start(); Thread.sleep(3000L); System.out.println("主线程退出"
); } //输出 still running. still running. 主线程退出

  GC线程就是一个守护线程,保持低优先级进行垃圾回收,不依赖系统资源,当所有用户线程退出之后,GC线程也就没有什么用了,会随即退出。因为如果没有用户线程了,也就代表没有垃圾会继续产生,也就不需要GC线程了。
  可以简单理解成守护线程为用户线程服务,当所有用户线程结束,也就不需要守护线程了。

技术
今日推荐
PPT
阅读数 128
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信