Thread.join()方法的使用

来源:互联网 发布:java aop记录日志 编辑:程序博客网 时间:2024/06/08 15:57

如果一个线程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;}@Overridepublic void run() {try {thread.join();} catch (InterruptedException e) {// TODO 自动生成的 catch 块e.printStackTrace();}System.out.println(Thread.currentThread().getName()+ " terminate.");}}/*** * 每个线程终止的条件是前驱线程的终止,每个线程等待前驱线程终止后,才从join()方法返回, * 当线程终止时,会调用自身的notifyAll()方法,通知所有等待在该线程对象上的线程。 */}

输出结果:



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

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

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

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