Java Thread.join()详解--父线程等待子线程结束后再结束
join是Thread类的一个方法,启动线程后直接调用,例如:
|
1
|
Thread t = new AThread(); t.start(); t.join(); |
在很多情况下,主线程生成并起动了子线程,如果子线程里要进行大量的耗时的运算,主线程往往将于子线程之前结束,但是如果主线程处理完其他的事务后,需要用到子线程的处理结果,也就是主线程需要等待子线程执行完成之后再结束,这个时候就要用到join()方法了。
在JDk的API里对于join()方法是:
join
public final void join() throws InterruptedException Waits for this thread to die. Throws: InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
写一个简单的例子来看一下join()的用法:
1.AThread 类
BThread类
TestDemo 类
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152classBThreadextendsThread {publicBThread() {super("[BThread] Thread");};publicvoidrun() {String threadName = Thread.currentThread().getName();System.out.println(threadName +" start.");try{for(inti =0; i <5; i++) {System.out.println(threadName +" loop at "+ i);Thread.sleep(1000);}System.out.println(threadName +" end.");}catch(Exception e) {System.out.println("Exception from "+ threadName +".run");}}}classAThreadextendsThread {BThread bt;publicAThread(BThread bt) {super("[AThread] Thread");this.bt = bt;}publicvoidrun() {String threadName = Thread.currentThread().getName();System.out.println(threadName +" start.");try{bt.join();System.out.println(threadName +" end.");}catch(Exception e) {System.out.println("Exception from "+ threadName +".run");}}}publicclassTestDemo {publicstaticvoidmain(String[] args) {String threadName = Thread.currentThread().getName();System.out.println(threadName +" start.");BThread bt =newBThread();AThread at =newAThread(bt);try{bt.start();Thread.sleep(2000);at.start();at.join();}catch(Exception e) {System.out.println("Exception from main");}System.out.println(threadName +" end!");}}打印结果:
1234567891011main start.//主线程起动,因为调用了at.join(),要等到at结束了,此线程才能向下执行。[BThread] Thread start.[BThread] Thread loop at 0[BThread] Thread loop at 1[AThread] Thread start.//线程at启动,因为调用bt.join(),等到bt结束了才向下执行。[BThread] Thread loop at 2[BThread] Thread loop at 3[BThread] Thread loop at 4[BThread] Thread end.[AThread] Thread end.//线程AThread在bt.join();阻塞处起动,向下继续执行的结果main end!//线程AThread结束,此线程在at.join();阻塞处起动,向下继续执行的结果。1234567891011121314151617publicclassTestDemo {publicstaticvoidmain(String[] args) {String threadName = Thread.currentThread().getName();System.out.println(threadName +" start.");BThread bt =newBThread();AThread at =newAThread(bt);try{bt.start();Thread.sleep(2000);at.start();//at.join(); //在此处注释掉对join()的调用}catch(Exception e) {System.out.println("Exception from main");}System.out.println(threadName +" end!");}}打印结果:
123456789101112main start.//主线程起动,因为Thread.sleep(2000),主线程没有马上结束;[BThread] Thread start.//线程BThread起动[BThread] Thread loop at 0[BThread] Thread loop at 1main end!//在sleep两秒后主线程结束,AThread执行的bt.join();并不会影响到主线程。[AThread] Thread start.//线程at起动,因为调用了bt.join(),等到bt结束了,此线程才向下执行。[BThread] Thread loop at 2[BThread] Thread loop at 3[BThread] Thread loop at 4[BThread] Thread end.//线程BThread结束了[AThread] Thread end.//线程AThread在bt.join();阻塞处起动,向下继续执行的结果五、从源码看join()方法
在AThread的run方法里,执行了bt.join();,进入看一下它的JDK源码:
123publicfinalvoidjoin()throwsInterruptedException {join(0L);}123456789101112131415161718192021publicfinalsynchronizedvoidjoin(longl)throwsInterruptedException{longl1 = System.currentTimeMillis();longl2 = 0L;if(l < 0L)thrownewIllegalArgumentException("timeout value is negative");if(l == 0L)for(; isAlive(); wait(0L));elsedo{if(!isAlive())break;longl3 = l - l2;if(l3 <= 0L)break;wait(l3);l2 = System.currentTimeMillis() - l1;}while(true);}单纯从代码上看: * 如果线程被生成了,但还未被起动,isAlive()将返回false,调用它的join()方法是没有作用的。将直接继续向下执行。 * 在AThread类中的run方法中,bt.join()是判断bt的active状态,如果bt的isActive()方法返回false,在 bt.join(),这一点就不用阻塞了,可以继续向下进行了。从源码里看,wait方法中有参数,也就是不用唤醒谁,只是不再执行wait,向下继续执 行而已。 * 在join()方法中,对于isAlive()和wait()方法的作用对象是个比较让人困惑的问题:
isAlive()方法的签名是:public final native boolean isAlive(),也就是说isAlive()是判断当前线程的状态,也就是bt的状态。
wait()方法在jdk文档中的解释如下:
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
在这里,当前线程指的是at。
Java Thread.join()详解--父线程等待子线程结束后再结束的更多相关文章
- 【转】Java Thread.join()详解
http://www.open-open.com/lib/view/open1371741636171.html 一.使用方式. join是Thread类的一个方法,启动线程后直接调用,例如: ? 1 ...
- Java Thread.join()详解(转)
(1)join方法是可以中断的(2)在线程joiner在另一个线程t上调用t.join(),线程joiner将被挂起,直到线程t结束(即t.isAlive()返回为false)才恢复 package ...
- Java Thread.join()详解
一.使用方式. 二.为什么要用join()方法 三.join方法的作用 join 四.用实例来理解 打印结果: 打印结果: 五.从源码看join()方法 一.使用方式. join是Thread类的 ...
- Java Thread.yield详解
这是Java中的一种线程让步方法,让Java中的线程从执行状态变成就绪状态,然后处理器再从就绪队列中挑选线程进行执行(优先级大的,被挑选的概率较大),这种转换也不确定,让或者不让都是取决与处理器,线程 ...
- Thread.join详解
/** * 如果某个线程在另一个线程t上调用t.join:那么此线程将被挂起,直到目标t线程的结束才恢复即t.isAlive返回为假 * * @date:2018年6月27日 * @author:zh ...
- Java多线程基础详解
基础概念进程进程是操作系统结构的基础:是一次程序的执行:是一个程序及其数据在处理机上顺序执行时所发生的活动.操作系统中,几乎所有运行中的任务对应一条进程(Process).一个程序进入内存运行,即变成 ...
- Java如何等待子线程执行结束
工作中往往会遇到异步去执行某段逻辑, 然后先处理其他事情, 处理完后再把那段逻辑的处理结果进行汇总的产景, 这时候就需要使用线程了. 一个线程启动之后, 是异步的去执行需要执行的内容的, 不会影响主线 ...
- Java线程池主线程等待子线程执行完成
今天讨论一个入门级的话题, 不然没东西更新对不起空间和域名~~ 工作总往往会遇到异步去执行某段逻辑, 然后先处理其他事情, 处理完后再把那段逻辑的处理结果进行汇总的产景, 这时候就需要使用线程了. 一 ...
- Java主线程如何等待子线程执行结束(转)
工作中往往会遇到异步去执行某段逻辑, 然后先处理其他事情, 处理完后再把那段逻辑的处理结果进行汇总的产景, 这时候就需要使用线程了. 一个线程启动之后, 是异步的去执行需要执行的内容的, 不会影响主线 ...
随机推荐
- bzoj 1597 [Usaco2008 Mar]土地购买——斜率优化dp
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1597 又一道斜率优化dp.负数让我混乱.不过仔细想想还是好的. 还可以方便地把那个负号放到x ...
- 在rebar发布的项目中添加监视工具
默认使用rebar创建的项目没法使用observer,可以如下操作 修改app.src {application, tcp_server, [ {description, ""}, ...
- erlang热部署
以下流程参考rebar的wiki,亲测 rebar的版本一定要注意,高版本对于下面两个指令有bug rebar generate-appups rebar generate-upgrade 经过一个个 ...
- FPGA噪声干扰
在FPGA高速AD采集设计中,PCB布线差会产生干扰.今天小编为大家介绍一些布线解决方案. 1.信号线的等长 以SDRAM或者DDRII为例,数据线,命令线,地址线以及时钟线最好等长,误差不要超过50 ...
- yii2 csrf验证原理分析
知识补充 因为yii2 csrf的验证的加解密 涉及到异或运算 所以需要先补充php里字符串异或运算的相关知识,不需要的可以跳过 ^异或运算不一样返回1 否者返回 0在PHP语言中,经常用来做加密的运 ...
- 【转】理解JMeter聚合报告(Aggregate Report)
Aggregate Report 是 JMeter 常用的一个 Listener,中文被翻译为“聚合报告”.今天再次有同行问到这个报告中的各项数据表示什么意思,顺便在这里公布一下,以备大家查阅. 如果 ...
- juc线程池原理(五):拒绝策略示例
概要 拒绝策略介绍 线程池的拒绝策略,是指当任务添加到线程池中被拒绝,而采取的处理措施.当任务添加到线程池中之所以被拒绝,可能是由于:第一,线程池异常关闭.第二,任务数量超过线程池的最大限制. 线程池 ...
- telnet WIN7设置回显办法
windows 2000及XP默认是关闭telnet回显的,这样在操作上很不方便,要让Telnet程序实现本地回显可以按如下步骤操作:1.在命令窗口中运行不带任何参数的telnet命令,执行 /hel ...
- mysql 内存体系结构--session
体系结构tmp_table_size & max_heap_table_size ,这个是会话级的内存结构mysql使用总内存 = global_buffers + thread_buffer ...
- Unity3D的坑系列:你真想发布WinPhone版吗?
Unity 4.2加入了支持WinPhone发布,本来是一件令人开心的事情,不过最近听了Unity技术支持的一个事情后就发现,原来发布WinPhone版也是一个坑. 实际上如果你用Unity做小游戏发 ...