gpt4 book ai didi

java - 调用thread.join()时如何通知lock

转载 作者:行者123 更新时间:2023-12-01 12:47:55 25 4
gpt4 key购买 nike

简单描述

  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() 的调用堆栈就像

加入 -> 加入(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;
}
}
}

main锁定了对象t并等待通知。我对何时何地调用通知感到有些困惑。 native 函数 stop0() 是否调用它?

最佳答案

看看这个:who and when notify the thread.wait() when thread.join() is called?

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

关于java - 调用thread.join()时如何通知lock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24507326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com