Thread.join()方法的使用

时间:2021-08-12 20:43:13

如果一个线程A执行了thread.join()语句,代表当前线程A等待thread线程终止后才从thread.join()方法返回 并且这个方法具有超时特性,可以添加参数设置

package myTestDeadlock;

import java.util.concurrent.TimeUnit;

public class Join {

/**
* @throws InterruptedException
* @Title: main
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param args 设定文件
* @return void 返回类型
* @throws
*/
public static void main(String[] args) throws InterruptedException {
Thread previous = Thread.currentThread();
for(int i=0; i<10; i++){
Thread thread = new Thread(new Domino(previous),String.valueOf(i));
thread.start();
previous = thread;
}
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+ " terminate.");

}
static class Domino implements Runnable{

private Thread thread;
public Domino(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
try {
thread.join();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ " terminate.");
}

}

/***
* 每个线程终止的条件是前驱线程的终止,每个线程等待前驱线程终止后,才从join()方法返回,
* 当线程终止时,会调用自身的notifyAll()方法,通知所有等待在该线程对象上的线程。
*/

}

输出结果:


Thread.join()方法的使用

jdk中Thread.join()方法的源码(进行了部门调整)

public final synchronized void join() throws InterruptedException{
//条件不满足,继续等待
while(isAlive()){
wait(0);
}
//条件符合,方法返回
}

  每个线程终止的条件是前驱线程的终止,每个线程等待前驱线程终止后,才从join()方法返回,

 当线程终止时,会调用自身的notifyAll()方法,通知所有等待在该线程对象上的线程。