簡體   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