This program shows the working of the ThreadObject.join() method. The join() method forces a thread to wait for another thread to die before it is allowed to continue executing. Or, put in another way, thread A may call thread B’s join() method if A wants to stop executing and wait for thread B to finish before A continues. Without t.join() – notice that t’s count is after main’s begin and end. This is because both the main and t threads execute independent of each other and since t sleeps, the main thread has plenty of CPU time to finish executing.
With t.join() - The output shows that T’s counting activity is between main’s begin and end. Now main waits for t to die 1st before continuing – because main calls t.join(). By calling this method, main tells the t thread that “I will join after you !”
Some extra experimenting : Call t.join() before calling t.start() – This means main is telling t that it wants to join at the end of t’s execution EVEN BEFORE t STARTED EXECUTING. t.join() will have no effect on main. Maybe t replies : “you may continue since I have not even started executing… do not wait for me.” Join only makes main wait if t is already started.
Can you shoot lasers out of your eyes? Don't look at this tiny ad: