继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

java 后台线程 daemon thread

守着星空守着你
关注TA
已关注
手记 211
粉丝 39
获赞 266

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

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP