美文网首页
join 线程详解

join 线程详解

作者: 山间草夫 | 来源:发表于2020-09-11 10:49 被阅读0次

Thread.join() 可以理解为阻塞, 当子线程在父线程中调用join的时候, 父线程会等子线程执行完毕才会继续执行下面的代码.
代码如下:

public class JoinTest {

    public static void main(String[] args) {
        try {
            ThreadB threadB = new ThreadB("ThreadB");
            threadB.start();
            threadB.join();
            System.out.println(" 主线程关闭");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class ThreadA extends Thread {
        public ThreadA(String name) {
            super(name);
        }

        public void run() {
            System.out.printf(" %s start\n", this.getName());
            // 延时操作
            for (int i = 0; i < 1000000; i++) {
            }
            System.out.printf(" %s end\n", this.getName());
        }
    }

    static class ThreadB extends Thread {
        public ThreadB(String name) {
            super(name);
        }

        @SneakyThrows
        public void run() {
            System.out.printf(" %s start \n", this.getName());
            // 延时操作
            for (int i = 0; i < 1000000; i++) ;
            ThreadA t1 = new ThreadA("threadA");
            t1.start();
            t1.join();
            System.out.printf(" %s end  \n", Thread.currentThread().getName());
        }
    }

}

这里的b线程中运行着a线程, 也就是说 a线程是b线程的子线程, b线程是主线程的子线程.
那么b线程的代码必须等a线程执行完成后才能继续执行, 而且, 主线程的 System.out.println(" 主线程关闭"); 必须等b线程执行完成后才能继续执行.
下面是控制台的打印结果:

 ThreadB start 
 threadA start
 threadA end
 ThreadB end  
 主线程关闭

今日分享结束, 路过点赞, 月入10w !

相关文章

网友评论

      本文标题:join 线程详解

      本文链接:https://www.haomeiwen.com/subject/kdpvektx.html