Thread.join()的真正含义

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/programmer_at/article/details/78934278

首先, 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()的定义。
这里写图片描述

这里写图片描述

展开阅读全文

没有更多推荐了,返回首页