Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread.join()

 
Manuj Bawa
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Can anyone post up a code example of just Thread.join(), Where should ThreadInstance.join() be placed? I tried writing this code:


To my understanding, the problem here is: when the compiler hits try catch block, main() is still the running thread, My question is: How do I make sure that join is called when a is the current running Thread.

Thanks,
Manuj
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a ("First") has to be the current thread you have to call b.join() from it, i.e. from MyRunnableA.run().
What are you trying to accomplish?
 
Manuj Bawa
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am just trying to write program that demonstrates join(). I wanted <a> to wait up till <b> finishes.

In the run() method of MyRunnableA, Can I say b.join()?

Thanks,
Manuj
 
Joe Sondow
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't say b.join() unless b is in scope. Here's a program that illustrates a way you could show what you've suggested:


[ April 15, 2005: Message edited by: Joe Sanowitz ]
 
Saurabh Khanna
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want a to wait up till b is finished then you will have to get reference b to a somehow and get a to call b.join(). Here is a modified version of your code which will do it for you:

I've just changed the constructor and the reference declaration, and tested it to see that a waits for b to finish (and it does...)




Hope this helps...

regards
Saurabh
 
Saurabh Khanna
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually you can also remove

the following from main, as that is joining main to b, main will wait until b is finished! (but we want a to wait until b is finished?)



Saurabh
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Manuj", welcome to JavaRanch! Please read our JavaRanch Naming Policy and change your displayed name to conform with it. In your case we require a displayed name in the format <first name> <family name> (in that order).
Thanks
-Barry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic