zoukankan      html  css  js  c++  java
  • 守护线程会不会执行finally?默认情况new thread怎么样确定守护状态?

    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的语句都有可能不被执行

  • 相关阅读:
    Puzzle, ACM/ICPC World Finals 1993, UVa227
    Puzzle, ACM/ICPC World Finals 1993, UVa227
    All in All, UVa 10340
    All in All, UVa 10340
    Box, ACM/ICPC NEERC 2004, UVa1587
    Box, ACM/ICPC NEERC 2004, UVa1587
    动态文本输出
    形态分析法
    粒子系统
    思维
  • 原文地址:https://www.cnblogs.com/silyvin/p/12052217.html
Copyright © 2011-2022 走看看