wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes using join() on multiple threads. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "using join() on multiple threads." Watch "using join() on multiple threads." New topic
Author

using join() on multiple threads.

Carlton Hanna
Greenhorn

Joined: Jul 29, 2009
Posts: 6
I'm wondering, if I have multiple worker threads and want the created thread to wait for them all to finish. Would this be the right way to do it:

Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Yes.

Although in a real program you would more likely write a loop to join all of the threads, rather than an unrolled loop.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Carlton Hanna wrote:I'm wondering, if I have multiple worker threads and want the created thread to wait for them all to finish. Would this be the right way to do it:



You mean to say that created Thread is Main Thread, and should it wait for the worker thread to finished their jobs.


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Isuru Sampath
Ranch Hand

Joined: Jun 26, 2003
Posts: 57
Won't this do rather than looping again to join the threads again???



No Winds No Waves
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3003
    
    9
Isuru: no. That would completely neutralize the point of using multiple threads. Every time you start a new thread, you wait until it completes, doing nothing else until it completes. In that case, you might as well do all the work in one thread - all benefits of using multiple threads have been lost.
Steven Rodeo
Ranch Hand

Joined: Mar 06, 2008
Posts: 72

You can use either a CyclicBarrier or a CountDownLatch. Its an elegant way for the main thread to wait for its worker threads to finish. Again it depends on your code wether you need to use a CyclicBarrier or a CountDownLatch.

_SM

Isuru Sampath
Ranch Hand

Joined: Jun 26, 2003
Posts: 57
Hi Mike,

Thanks a lot for your explanation. Saved me from lots of trouble. Now I get it. The moment I call the join() method my calling thread will start waiting untill the spawned thread completes.
Isuru Sampath
Ranch Hand

Joined: Jun 26, 2003
Posts: 57
Hi Steven,

Thanks for your suggestion. CountDownLatch is what I need. Thanks again.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: using join() on multiple threads.
 
Similar Threads
producer-multiple consumers
Blocking queue Implementation
dynamically adding to queue
join() method; guarenteed behaviour
Limit concurrent threads; report successful execution; terminating hung threads