Thread中join方法源码阅读

发布时间 2023-08-30 14:44:10作者: HHHuskie

以JDK11为例,共3个join方法

一、核心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");
        }
     // 等待时间为0
        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
     // 利用System.currentTimeMillis()计算剩余等待时间
while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } }

二、更精细的join方法

public final synchronized void join(long millis, int nanos)
    throws InterruptedException {

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        join(millis);
    }

三、最常用的join方法

public final void join() throws InterruptedException {
        join(0);
    }