Thread.join()的真正含义

首先, Thread.join() 并没有将线程合并起来~
任何疑惑都先从Java Doc开始,
这里写图片描述

stackoverflow上有个极好的例子:
这里写图片描述
1. After the main thread creates and starts the t1 and t2 threads. There are 3 threads running in parallel: main, t1, t2
2, The main thread calls t1.join() to wait for the t1 thread to finish.
3. The t1 thread completes and the t1.join() method returns in the main thread. Note that t1 could already have finished before the join() call is made in which case the join()call will return immediately.
4. The main thread calls t2.join() to wait for the t2 thread to finish.
5. The t2 thread completes (or it might have completed before the t1 thread did) and the t2.join() method returns in the main thread.
虽然main, t1, t2都在runing, 但是到了t1.join()这句话开始,main必须等待t1, t2运行结束后才可以往下执行
举个栗子,
这里写图片描述
倘若t没有运行结束, 那么main就会一直阻塞在”t.join()“这里。
倘若将t.join()注释掉,就可以运行结束。运行效果如下:
这里写图片描述

回到最上面的栗子(灰颜色代码)
线程t1, t2可以在main()调用join()函数之前运行结束。这时候,join() will not wait but will return immediately.

还有一点,很重要: t1.join() means cause t2 to stop until t1 terminates?
No. The main thread that is calling t1.join() will stop running and wait for the t1 thread to finish. The t2 thread is running in parallel and is not affected by t1 or the t1.join() call at all.
所以这时候可能出现一下情况,
这里写图片描述

In terms of the try/catch, the join() throws InterruptedException meaning that the main thread that is calling join() may itself be interrupted by another thread.

说人话,在线程t中调用了另外一个线程innerThread.join(), 倘若这时候线程t受到外部的影响,比如 interrupted by main thread中的”t.interrupt()”, 此时 innerThread.join()会抛出异常InterruptedException,此时线程t需要处理这个异常。然而,并不影响线程innerThread的运行的。请看下面的例子:
这里写图片描述
运行结果如下:
这里写图片描述
innerThread抛出异常并没有影响到它本身的运行。

而在main()线程中调用了t.interruput×()导致了线程t接收到了来自innerThread抛出异常,符合Thread.interrupt()的定义。
这里写图片描述

这里写图片描述

  • 8
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值