亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

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下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消