Thread线程解析。join的作用将thread纳入当前线程

Thread 的join的作用是将thread 加入到当前的线程
看个例子就很好理解了

 public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Thread thread1 = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            System.out.println("thread1 IM work");
                            Thread.sleep(5000);
                            System.out.println("thread1 IM done");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });

                Thread thread2 = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            System.out.println("thread2 IM work");
                            Thread.sleep(10000);
                            System.out.println("thread2 IM done");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
                thread1.start();
                thread2.start();
                try {
                    thread1.join();
                    thread2.join();
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        try {
            thread.join();
            System.out.println("IM done");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

一共三个线程 一个父线程thread 两个子线程 thread1 ,thread2。
输出日志

thread1 IM work
thread2 IM work
thread1 IM done
thread2 IM done
IM done

 thread1.join();
 thread2.join();

是将thread1 thread2 加入到thread 父线程 ,thread会等待两个子线程完成,thread.join() 是加入当前main所在的线程 ,所以IM done 是所有线程运行完之后才打印的。
可以测试分别把
thread.join()和
thread1.join();
thread2.join();
去掉 看下打印的日志就知道区别了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值