为了账号安全,请及时绑定邮箱和手机立即绑定

java 后台线程 daemon thread

标签:
Java

java中的后台线程,是Thread实例设置了setDaemon(true),即将daemon属性设置为了true。 当程序中没有活动的前台线程时,后台线程会被jvm中断,退出程序,这是后台线程和普通线程的唯一区别。需要注意将线程设置为daemon的时机必须在其运行之前。

我们可以使用下面实例来实际看下后台进程和前台进程之间的区别。

下面代码我们把Thread实例t的daemon属性设置为true。

package cn.outofmemory.concurrent; import java.util.Date; import java.lang.Thread; public class App { public static void main(String[] args) throws Exception { Runnable r = new Runnable() { @Override public void run() { String daemon = (Thread.currentThread().isDaemon() ? "daemon" : "not daemon"); while (true) { System.out.println("I'm running at " + new Date() + ", I am " + daemon); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("I was interrupt, I am " + daemon); } } } }; Thread t = new Thread(r); t.setDaemon(true); t.start(); Thread.sleep(3000); System.out.println("main thread exits"); } }

 运行上面程序,输出如下内容后程序就退出了。

I'm running at Sat May 03 17:13:08 CST 2014, I am daemon I'm running at Sat May 03 17:13:09 CST 2014, I am daemon I'm running at Sat May 03 17:13:10 CST 2014, I am daemon main thread exits

可以看到在主线程退出之后,deamon线程也就被终止了,同时程序也就退出了。

我们对上面程序稍作改动,将t.setDaemon(true)注释掉,再看下运行结果。

package cn.outofmemory.concurrent; import java.util.Date; import java.lang.Thread; public class App { public static void main(String[] args) throws Exception { Runnable r = new Runnable() { @Override public void run() { String daemon = (Thread.currentThread().isDaemon() ? "daemon" : "not daemon"); while (true) { System.out.println("I'm running at " + new Date() + ", I am " + daemon); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("I was interrupt, I am " + daemon); } } } }; Thread t = new Thread(r); //t.setDaemon(true); t.start(); Thread.sleep(3000); System.out.println("main thread exits"); } }

运行程序的输出如下:

I'm running at Sat May 03 17:15:48 CST 2014, I am not daemon I'm running at Sat May 03 17:15:49 CST 2014, I am not daemon I'm running at Sat May 03 17:15:50 CST 2014, I am not daemon main thread exits I'm running at Sat May 03 17:15:51 CST 2014, I am not daemon I'm running at Sat May 03 17:15:52 CST 2014, I am not daemon

可以看到在主线程退出之后,t线程还在继续执行,这是因为线程t默认情况下是非守护线程,尽管主线程退出了,他还是在继续执行着。

需要注意设置线程是否为守护线程必须在其执行之前进行设置,否则会抛出异常IllegalThreadStateException。这一点可以从Thread类的setDaemon(boolean)的源码中得到求证。如下源码:

    public final void setDaemon(boolean on) { checkAccess(); if (isAlive()) {     throw new IllegalThreadStateException(); } daemon = on;     }

可以看到如果线程在live状态调用setDaemon会抛出异常。

原文链接:http://outofmemory.cn/java/java.util.concurrent/daemon-thread

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消