一、 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;
}
}
}
本文详细解析了Java中Thread.join()方法的功能与使用。当线程A调用线程B的join()方法时,A将等待B执行完毕后继续运行。文章通过代码示例展示了join()方法的具体实现,包括其对线程同步的影响。
8506

被折叠的 条评论
为什么被折叠?



