Thread.join()方法的使用

如果一个线程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()方法,通知所有等待在该线程对象上的线程。
 */

}

输出结果:



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

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

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

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


 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值