File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Clarify Use of the join method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Clarify Use of the join method" Watch "Clarify Use of the join method" New topic

Clarify Use of the join method

d jones
Ranch Hand

Joined: Mar 13, 2006
Posts: 76

If we have

Here I would have thought that Thread b would stop running as soon as the line a.join() was executed.
But it doesn't it continues to run.

Could anyone please explain to me how the join method is working in this example? Shouldn't the a.join() line have caused any executing threads to be halted and not run again until a completed?

I understand if I have 1 thread and start it in the main method that it puts the main method on hold until the thread on which I call join completes.

But what if we wanted 1 thread to run after another, as in the above code, where I want thread b to run only when thread a has completed?

Many Thanks
Henry Wong

Joined: Sep 28, 2004
Posts: 20517

When a thread calls the join() method of a thread object -- it will wait until the thread represented by that thread object completes. Nothing else is affected.

In your example, the main thread will wait until thread A completes. Period. Thread B (or any other thread) does not wait til thread A completes. Nor does the main thread waits for any other thread to complete.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Main is a controlling thread, so you can delay the starting of thread b until the main thread has joined with thread a.

You could also pass thread a to thread b and have thread b join thread a.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
I agree. Here's the link:
subject: Clarify Use of the join method
It's not a secret anymore!