在使用线程实现诸如A->B->C这样的时候,想到的无疑就是join()方法,看了一下方法的源码,然后也是各方搜集了一下资料才明白其中的原理,这篇文章就记录一下当时的困惑。
在我查看源码注释的时候,发现了两个线程this thread和current thread,this指的当然是调用方法的this对象的线程,而current却是指的是当前正在运行的线程,请注意他们的区别。
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*等待this线程死亡,参数0即代表如果不唤醒会一直等下去
* <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.
*这里实际上就已经提到了,所有线程都会在死亡的时候调用notifyAll方法唤醒所有阻塞在这个锁上的线程
* @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.
*/
//JDK1.8的join()方法
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()) { //判断this线程是否存活,如果this线程已经执行完成死亡,那么current线程直接执行
//并不会进入wait()方法
wait(0); //开始我在这里纠结了一会儿,虽然是this线程调用等待,但是wait实际上是current线程进行阻塞
//,也即是当前运行线程阻塞,注意是当前线程拿的这个锁那么也只有这个线程能释放锁
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}