一、 Thread.join()的实现功能
如果有两个线程Thread A和Thread B,且在A中调用了B.join()方法,则线程A会等待线程B执行结束后继续执行。上述即为Thread.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()) {
wait(0); //检查被调用的线程是否存活,若存活则继续等待
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}