Java Daemon 后台线程结束时不执行finally语句

一般情况下,try catch finally 语句块中的finally一般都会执行的,即便try或者catch中有return语句,当try catch中使用System.exit()结束的时候,则不会执行finally语句块。这点相信大家都挺清楚的。不过,当finally语句块是在Daemon 后台子线程中的run()被执行被执行的时候,情况就有点不一样。

Java Daemon 后台子线程结束时不执行finally语句。

就这个问题,刚好写了个小Demo灌灌水。

Main()中开启了一个Daemon线程,每隔一毫秒打印一次,主线程中睡5毫秒后打印end结束,Daemon线程直接退出,不打印finally。

class ThreadDaemonDemo extends Thread {

	@Override
	public void run() {
		System.out.println(this + " is daemon " + isDaemon());
		try {
			while (true) {
				Thread.sleep(1);
				System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("finally "); //this part will not reach 
		}
	}
}

public class TestThread {
	public static void main(String args[]) {
		Thread t1 = new ThreadDaemonDemo();
		t1.setDaemon(true);	// setDaemon() must be called before start() 
		t1.start();
		try {
			Thread.sleep(5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("end ......");
	}
}

附上本人机器的结果

Thread[Thread-0,5,main] is daemon true
1490020816896 Thread-0
1490020816898 Thread-0
1490020816899 Thread-0
1490020816900 Thread-0
end ......

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值