简体   繁体   English

thread.join()在概念上如何工作?

[英]How does thread.join() work conceptually?

From the docs: 从文档:

The join method allows one thread to wait for the completion of another. join方法允许一个线程等待另一个线程的完成。 If t is a Thread object whose thread is currently executing, 如果t是当前正在执行线程的Thread对象,

t.join();

causes the current thread to pause execution until t's thread terminates 导致当前线程暂停执行,直到t的线程终止

What I can't get my head around is that this is a method on a thread that's different to one it's being called from. 我无法理解的是,这是线程上的一种方法,该方法不同于被调用的方法。 So if a thread t1 calls another thread's t2.join() , t2 knows nothing about t1 . 因此,如果线程t1调用另一个线程的t2.join() ,则t2t1一无所知。 So what's actually happening under the hood to make t1 wait for t2 for finish? 那么,要使t1等待t2完成,实际上是在发生什么呢?

By looking at the Java source code: 通过查看Java源代码:

calling t2.join() from t1 will make t1 wait on t2 object (t2 is a Thread , which is a subclass of Object ). 从t1调用t2.join()将使t1等待t2对象(t2是Thread ,这是Object的子类)。 The wait will be forever as long as t1 is alive. 只要t1仍然存在,等待将永远存在。 When t2 thread finishes its work, it will call Object.notifyAll() so t1 awakens. 当t2线程完成其工作时,它将调用Object.notifyAll()以便t1唤醒。

The classic implementation of Thread.join (other implementations are possible, is to lock the Thread object, test to see if is alive and if not wait on the Thread object. As a thread exits, it locks its instance and calls notifyAll . Thread.join的经典实现(可能的其他实现是锁定Thread对象,测试是否存在,是否不wait Thread对象。当线程退出时,它将锁定其实例并调用notifyAll

The choice of a public object as the lock is unfortunate. 选择公共对象作为锁是不幸的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM