• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Waiting for all threads to stop

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

How do I ensure all threads finish executing before main() continues. I used something like this:


for (int i : NUM_THREADS) {
threads.start();
}

for (int i : NUM_THREADS) {
threads.join(); // line 1
}

Does join() queue up the execution of threads ? For example, if threads 1 and 2 are running, main will wait at line 1 for thread 1 to die before going to the start of "for" loop. This will effectively rule out the concurrent execution model of the thread. Is there any other way of doing this? Or am I misinterpreting this?

Let me know
Thanks
M
 
Marshal
Posts: 67275
170
Mac Mac OS X IntelliJ IDE jQuery Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Krishna",

There aren't many rules that you need to worry about here on the Ranch, but one that we take very seriously regards the use of proper names. Please take a look at the JavaRanch Naming Policy and adjust your display name to match it.

In particular, your display name must be a first and a last name separated by a space character, and must not be obviously fictitious.

Thanks!
bear
JavaRanch Sheriff
 
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Join method will block only the thread that's calling it. In your case main thread will be blocked until the current iterative thread has completed the job. This doesn't mean that other two threads (from you example) will be executed sequentially. They will continue to run in parallel expect that main thread will "wait on each thread sequentially" to complete .

Calling join() method on the child thread may cause main application to hang if child thread is stuck. The best way is to have a timeout on join method. Look at the java doc.
 
Krishna Attravanam
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, I see what you are saying. That helps. THanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!