finally throw return 中,线程的状态及interrupt 守护线程在退出的时候并不会执行finnaly块中的代码
线程池造成服务器内存泄漏 中所述,新建线程默认上使用建立线程时的当前线程所处的守护状态
本文予以验证:
package fin; /** * Created by joyce on 2019/12/16. */ public class TestDaemonFinally { public static void main(String []f) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { try { try { /** * 测试母线程守护,子线程? */ Thread tt = new Thread(new Runnable() { @Override public void run() { } }); System.out.println("tt" + tt.isDaemon()); Thread.sleep(2000); System.out.println("守护线程1的try会不会执行?"); } catch (InterruptedException e) { e.printStackTrace(); } } finally { System.out.println("守护线程1的finally会不会执行?"); } } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { try { System.out.println("守护线程2的try会不会执行?"); } catch (Exception e) { e.printStackTrace(); } } finally { System.out.println("守护线程2的finally会不会执行?"); } } }); // 证明new thread方式默认也是非守护线程 // System.out.println(thread.isDaemon()); thread.setDaemon(true); thread.start(); System.out.println(thread2.isDaemon()); thread2.setDaemon(true); thread2.start(); Thread.sleep(1000); System.out.println("exit"); } }
false
false
守护线程2的try会不会执行?
守护线程2的finally会不会执行?
tttrue
exit
结论:
1 证明new thread方式,守护状态继承母线程
2 守护线程有时会执行finally,有时不会,并不是守护线程一定不会执行finally,问题不在于finally,问题在于守护
守护线程在用户线程退出时,随机退出,包括但不限于finally的语句都有可能不被执行