[Java][Thread] Thread的join方法 为何可以让调用的线程等待被调用的线程执行完? - Gukie/learning GitHub Wiki

refer: https://juejin.im/post/5a72d4bd518825735300f37b#heading-10

  1. 因为join方法是Thread的一个 synchronized方法,
  2. 调用它的时候需要获取被调用线程的锁,所以在获取锁的阶段,调用线程会被Blocked;
  3. 当获取到锁的时候,会去check 线程是否活着,如果活着则调用 wait方法,该方法会将 调用线程 放入等待队列 进入Blocked状态; 直至被调用线程结束
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;
        }
    }
}