Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Join() method in Java

 
Matloob Hussain
Ranch Hand
Posts: 37
Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Here is the code example, the output of two methods named method1() and method2() is different. The code difference in second method is thread T2 is started after join() method which is invoked on thread T1 but in first method, both threads T1 and T2 are started first and then join() method is invoked.

Could anyone please explain it..... thanks



 
Piyush Joshi
Ranch Hand
Posts: 207
Eclipse IDE Firefox Browser jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not very good in threads but as far as I understand it: (if I am wrong please somebody correct me)

t1.join() call here in method1 and method2 will block the main thread from becoming runnable till the thread t1 completes.

In method1 we start thread t2 before we call t1.join() so t1 and t2 both will be in runnable state and

In method2 we call t1.join() before we start thread t2, so as soon as we call t1.join() the main thread will be blocked.
Therefore t2 will now be started only after the t1 completes execution.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose there are two threads T1 and T2 are running . and T1 starts T2 and now if you say T2.join() [in the T1 thread flow], then T1 blocks until T2 complete the job.
 
Suhrid Karthik
Ranch Hand
Posts: 58
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In method1(), there is a possibility of both T1 and T2 running at the same time. In method2(), the main thread waits for T1 to complete by join()'ing itself to the end of T1. When T1 completes, the main thread resumes and starts T2.
 
Piyush Joshi
Ranch Hand
Posts: 207
Eclipse IDE Firefox Browser jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seetharaman Venkatasamy wrote:Suppose there are two threads T1 and T2 are running . and T1 starts T2 and now if you say T2.join() [in the T1 thread flow], then T1 blocks until T2 complete the job.


Yes you are right.

T2.join() will block the current executing thread. that is T1 if you call T2.join() from T1
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic