join方法就是挂起调用线程,直到被调用线程执行完毕后再继续执行。例:threadB线程中threadA的join方法,所以threadB需在threadA执行完毕后才继续执行join后的代码,而主线程执行threadB.join()
,所以最终主线程需等threadA和threadB执行完毕后才继续。
@Slf4j
public class JoinThread {
public static void join() throws InterruptedException {
long startTime = System.currentTimeMillis();
Thread threadA = new Thread(() -> {
try {
log.info("threadA start");
Thread.sleep(4000);
log.info("threadA end");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread threadB = new Thread(() -> {
try {
threadA.join();
log.info("threadB start");
Thread.sleep(3000);
log.info("threadB end");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threadA.start();
threadB.start();
threadB.join();
log.info("run time [{}]", startTime - System.currentTimeMillis());
log.info("main thread end");
}
}
输出结果:
- threadA start
- threadA end
- threadB start
- threadB end
- run time [-7149]
- main thread end
Thread类中的join方法:
public final synchronized void join(long millis)
throws InterruptedException {
//进入方法时间
long base = System.currentTimeMillis();
//执行时间
long now = 0;
//如果等待超时时间小于0抛出异常
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
//等待超时时间为0则始终挂起,指定被调用线程执行完毕
if (millis == 0) {
//需要注意,如果当前线程未被启动或者终止,则isAlive方法返回false
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
//执行挂起时间
long delay = millis - now;
//如果剩余的等待时间小于等于0,则终止等待
if (delay <= 0) {
break;
}
//等待指定时间
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}