Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

join() method of class Thread

 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi:
I am a little confused about how join() works. Which thread will stop, and which one will continue.
Thread t = new Thread();
Thread x = new Thread();
t.start();
t.join();
x.start();
and also this case:
t.start();
join()
x.start();
join();
Thanks
 
Ray Stojonic
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Hanna,
here's my understanding of it, any corrections are welcome.
in the first example when you t.start(), t begins running, the next step in the current method is t.join(). t.join() won't return to the current method until t has died, the current method has to wait until t.join() returns to continue. When t dies, the current method can continue and call x.start() then exit.
The second case is the same, except now the current method waits for t to die, then x, then exits.
 
Dhanashree Mankar
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Hanna Habashy:
hi:
I am a little confused about how join() works. Which thread will stop, and which one will continue.
Thread t = new Thread();
Thread x = new Thread();
t.start();
t.join();
x.start();
and also this case:
t.start();
join()
x.start();
join();
Thanks

1>
in this case t.start will start a new thread.it will call run() method.
and then call to join(). means main threads wait till new thread completes it's work or till new thread dies.Then new object of thread class "x" starts new thread.
2>
second case is also same except join is not called with object It is not necessary also since join is instance method of thread class.also here x starts new thread and then wait for it to complete by calling join
 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all. It is now clearer than before.
But, I have another quistion. In the case of using join(), one can guarnatee the order in which threads are excuted? I know it is up to the schadualer, but if I can can force main thread to wait before it runs another thread, then I am telling to the schadualer which thread to run first.
Am I correct?
Hanna
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic