为什么join会阻塞主(父)线程?

问题来源

如下测试代码,输出的结果是主线程等待子线程 t 执行完成后,才会打印test,这是为什么?

	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(() -> {
			System.out.println("t start");
			try {
				// 等待2秒
				Thread.sleep(2000);
//				System.out.println(Thread.currentThread().getName());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("t end");
		});
		t.start();
		t.join();
//		System.out.println(Thread.currentThread().getName());
		System.out.println("test");
	}

输出为

t start
t end
test

原因分析(Thread的源码)

Thread在join方法中调用了自己的join(long timeout)join(long timeout)方法。

public final void join() throws InterruptedException {
	join(0);
}

在这里需要先说明一下wait方法的作用:

wait的作用是释放对象锁,释放CUP资源,使当前线程阻塞,进入对象的wait set,直到被通知、被中断或timeout到期。

当前线程指的是调用t.wait(0)方法的线程,很显然是主线程调用的t.join(),进而调用的t.wait(0),所以join是阻塞主(父)线程,而非子线程。

这里将子线程的变量名从 t 换成 o会更好理解,子线程对象在调用wait(0)的时候是以一个普通对象的身份,而非线程。

/**
 * Waits at most {@code millis} milliseconds for this thread to
 * die. A timeout of {@code 0} means to wait forever.
 *
 * <p> This implementation uses a loop of {@code this.wait} calls
 * conditioned on {@code this.isAlive}. As a thread terminates the
 * {@code this.notifyAll} method is invoked. It is recommended that
 * applications not use {@code wait}, {@code notify}, or
 * {@code notifyAll} on {@code Thread} instances.
 *
 * @param  millis
 *         the time to wait in milliseconds
 *
 * @throws  IllegalArgumentException
 *          if the value of {@code millis} is negative
 *
 * @throws  InterruptedException
 *          if any thread has interrupted the current thread. The
 *          <i>interrupted status</i> of the current thread is
 *          cleared when this exception is thrown.
 */
public final synchronized void join(long millis)
throws InterruptedException {
	long base = System.currentTimeMillis();
	long now = 0;

	if (millis < 0) {
		throw new IllegalArgumentException("timeout value is negative");
	}

	if (millis == 0) {
		while (isAlive()) {
			// 这个wait相当于 this.wait(0)
			// 也相当于 t.wait(0)
			wait(0);
		}
	} else {
		while (isAlive()) {
			long delay = millis - now;
			if (delay <= 0) {
				break;
			}
			wait(delay);
			now = System.currentTimeMillis() - base;
		}
	}
}

何时唤醒?

关于何时主线程会被唤醒这个问题的答案,不在 jdk 的源码中,而是在 jvm 源码中。本人暂时还没研究这么深,惭愧。但从 join 方法的注释中可以找到一点线索:As a thread terminates the {@code this.notifyAll} method is invoked,当线程终止时,this.notifyAll 方法会被调用。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值