Thread嵌套Thread

一个线程Thread1嵌套线程Thread2,使用Thread1.join()不会在Thread2完成之后继续执行。

public class Test1 {
    private static Thread t4;
    static Thread t1 = new Thread(){
        @Override
        public void run(){
            System.out.println("1");
        }
    };
    static Thread t2 = new Thread(){
        @Override
        public void run(){
            try {
                t4 = new Thread(){
                    @SuppressWarnings("static-access")
                    @Override
                    public void run(){
                        try {
                            t4.sleep(2000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        System.out.println("4");
                    }
                };
                t4.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("2");
        }
    };
    public static void main(String[] args){
        t2.start();
        try {
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.start();
        
    }
}

执行结果

2
1
4

t1只会让t2执行完毕,不会等待t2内部的t4执行完毕。

猜你喜欢

转载自my.oschina.net/u/2984758/blog/854038