繁体   English   中英

调用thread.join()时如何通知锁

[英]how to notify lock when calling thread.join()

简单描述

  public static void main(String[] args ){

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread stopped");
        }
    });

    try {
        t.start();
        t.join();
        System.out.println("task completed");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
   }

t.join()主线程等待其子线程t死亡。 t.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;
    }
}
}

主体锁定对象t并等待通知。 我在何时何地调用通知时有些困惑。 原生函数stop0()调用它吗?

看一下: 谁以及何时在调用thread.join()时通知thread.wait()?

run()完成之后,Thread子系统将调用notify()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM