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.
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.
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.
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.
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
Piyush
This cake looks terrible, but it tastes great! Now take a bite out of this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss