public class Thread implements Runnable {
//底层是使用wait()实现
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) {//参数为0时会一直等待线程结束
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
//防止虚假唤醒,因为wait会被notify和notifyAll唤醒
//唤醒后需要等待的时间是millis减去已经等待的时间
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
public final void join() throws InterruptedException {
join(0);
}
}