gpt4 book ai didi

java - java中join()方法的JVM内部工作

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

简单地说,Thread 的 join() 方法内部是如何工作的,我知道使用 join() 方法可以将一个线程加入到另一个线程的末尾。

例如,如果我们在主线程中使用thread.join(),那么主线程应该等待,直到Thread线程的run方法完全完成。但是它在内部是如何发生的,这会将主线程的堆栈附加到线程堆栈的末尾吗?我很困惑,因为两个线程不能共享同一个堆栈。如果我错了,请纠正我。

最佳答案

这是 Oracle JDK 的实现(如 jdk1.8.0_05/src.zip 中所示)

/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*
* @param millis
* the time to wait in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
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;
}
}
}

如您所见,没有发生任何奇特的堆栈操作。他们只是使用 wait 和 notification 方法让一个线程等待,直到另一个线程通知它终止。

关于java - java中join()方法的JVM内部工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23957736/

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