简体   繁体   中英

How does thread.join() work conceptually?

From the docs:

The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,

t.join();

causes the current thread to pause execution until t's thread terminates

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 . So what's actually happening under the hood to make t1 wait for t2 for finish?

By looking at the Java source code:

calling t2.join() from t1 will make t1 wait on t2 object (t2 is a Thread , which is a subclass of Object ). The wait will be forever as long as t1 is alive. When t2 thread finishes its work, it will call Object.notifyAll() so t1 awakens.

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 .

The choice of a public object as the lock is unfortunate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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