猿问

java的join

在main函数里面调用了join,查看了join的源码,调用join会转换为调用wait(0),比如下面的代码

public static void main(String[] args) {
    Thread r1 = new Thread(new X("r1"))
    r1.start();
    try {
        r1.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("Main finished");
}

但是,一般说A调用了wait则需要使用notify或者notifyAll唤醒线程A,而在join的代码当中并没有看到这两个函数对main线程的notify,那么main是怎么从join里面的wait(0)出来再进行循环判断的?(下面是join的源码,调用join(),在join()内部会直接调用join(0),也就是下面这个函数)

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;
        }
    }
}
蝴蝶刀刀
浏览 424回答 1
1回答

慕勒3428872

Thread执行完成后 会自动实现notifyAll功能,这个属于jvm c++层面的东西,所以java代码中是不需要显示的notify的
随时随地看视频慕课网APP

相关分类

Java
我要回答