谁以及何时在调用 thread.join() 时通知 thread.wait()? [英] who and when notify the thread.wait() when thread.join() is called?
问题描述
thread.join()
将调用 thread.wait()
,但是谁和何时通知(使用 thread.notify()
还是 notifyAll()
)thread.wait()
?
thread.join()
will call thread.wait()
, but who and when notifies (either with thread.notify()
or notifyAll()
) the thread.wait()
?
众所周知,线程加入会等待线程完成,但谁会调用notify呢?
As we know, thread join will wait for the thread to be completed, but who calls notify on it?
推荐答案
哦,你说的是 Thread
对象本身的内部.在 join()
内部,我们确实看到了一个 wait()
.类似的东西:
Oh, you are talking about inside of the Thread
object itself. Inside of join()
we do see a wait()
. Something like:
while (isAlive()) {
wait(0);
}
notify()
由 Thread
子系统处理.当 run()
方法完成时,会在 Thread
对象上调用 notify()
.我不确定是否可以看到实际调用 notify()
的代码——它似乎是在本机代码中完成的.
The notify()
for this is handled by the Thread
subsystem. When the run()
method finishes, the notify()
is called on the Thread
object. I'm not sure if the code that actually calls notify()
can be seen -- it seems to be done in native code.
没有用户代码需要对该 Thread
对象调用 notify()
.Java Thread
代码在内部处理这个.一旦线程完成,join()
调用将返回.
No user code needs to call notify()
on that Thread
object. The Java Thread
code handles this internally. Once the thread finishes, the join()
call will return.
例如,以下代码将正常执行,join()
调用将正常返回,无需任何 wait()
或 notify()
> 电话.
For example, the following code will execute fine and the join()
call will return fine without any wait()
or notify()
calls.
Thread thread = new Thread(new Runnable() {
public void run() {
// no-op, just return immediately
}
});
thread.start();
thread.join();
请务必注意,可能不应依赖此行为.notify()
调用是线程系统内部的.如果您正在等待线程完成,您应该使用 join()
.
It is important to note that this behavior should probably not be relied upon. The notify()
call is internal to the thread system. You should use join()
if you are waiting for a thread to finish.
这篇关于谁以及何时在调用 thread.join() 时通知 thread.wait()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!