有人可以在Java Thread类中解释join方法吗?
public final synchronized void join(long millis) throwsInterruptedException {
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;
}
}
}
等待(0)让主线程等到它完成。线程正在调用等待自己?据我所知,它必须锁定自己来调用wait()方法?完成后如何通知主线程?
How does wait(0) make the main thread wait until it finishes. Thread is calling wait on itself? As far as my understanding it must have a lock on itself to call wait() method? How does it notify the main thread when it finishes?
文档解释了逻辑:
此实现使用循环
this.wait
调用this.isAlive
。当一个线程终止时,会调用this.notifyAll
方法。建议应用程序不使用等待
,通知
或notifyAll
onThread
instances。
This implementation uses a loop of
this.wait
calls conditioned onthis.isAlive
. As a thread terminates thethis.notifyAll
method is invoked. It is recommended that applications not usewait
,notify
, ornotifyAll
onThread
instances.
所以这个实现依赖于这样的事实: Thread
对象不仅代表一个线程,而且也像Java中的任何其他对象一样对象。因此,它继承自 Object
,有自己的监视器并且可以同步,有线程等待
就可以了,等等。
So this implementation relies on the fact that the Thread
object does not just represent a thread, but is also an object like any other object in Java. As such, it inherits from Object
, has its own monitor and can be synchronized, have threads wait
ing on it, etc.
它必须锁定自己才能调用
wait()
方法?
是的。事实上,这种方法被声明为 synchronized
。所以它在Thread实例本身上同步。一旦你进入它,你有 Thread
实例的监视器。然后当调用 wait
时,你放弃它,所以其他线程可以做同样的事情。
Yes. And indeed, this method is declared synchronized
. So it synchronizes on the Thread instance itself. Once you are inside it, you have the Thread
instance's monitor. Then when wait
is called, you relinquish it, so other threads can do the same thing.
这可能是有点混乱。您当前运行的线程是线程A.您在线程B上使用 join
。此处正在同步的对象是线程B的实例,这会导致线程A等到在同一个(B)实例上调用 notifyAll
。
This might be a bit confusing. Your currently running thread is thread A. You are using join
on thread B. The object being synchronized on here is the instance of thread B, and this causes thread A to wait until notifyAll
is called on the same (B) instance.
当线程B完成时,它调用 notifyAll
在自己的实例上。因此,任何在线程B实例上的等待
中被阻止的线程都将被通知。
When the thread B finishes, it calls notifyAll
on its own instance. So any threads that are blocked in a wait
on thread B's instance will be notified.