Java线程 - 后台线程 daemon thread

来源:互联网 发布:应用中心源码 编辑:程序博客网 时间:2024/05/22 06:29

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() {@Overridepublic 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 daemonI'm running at Sat May 03 17:13:09 CST 2014, I am daemonI'm running at Sat May 03 17:13:10 CST 2014, I am daemonmain 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() {@Overridepublic 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 daemonI'm running at Sat May 03 17:15:49 CST 2014, I am not daemonI'm running at Sat May 03 17:15:50 CST 2014, I am not daemonmain thread exitsI'm running at Sat May 03 17:15:51 CST 2014, I am not daemonI'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会抛出异常。

0 0
原创粉丝点击