Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Waiting for all threads to stop  RSS feed

 
Krishna Attravanam
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
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65826
134
IntelliJ IDE Java jQuery Mac Mac OS X
  • 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
 
Purushoth Thambu
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!