The join() method

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

Syntax:


\begin{lstlisting}
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
\end{lstlisting}

Example


\begin{lstlisting}
class TestJoinMethod1 extends Thread{
public void run(){
...
...System.out.println(e);}
\par
t2.start();
t3.start();
}
}
\end{lstlisting}

Test it Now


\begin{lstlisting}
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
\end{lstlisting}

As you can see in the above example,when t1 completes its task then t2 and t3 starts executing. Following is the program that serves as an example of join(long miliseconds) method.


\begin{lstlisting}
lass TestJoinMethod2 extends Thread{
public void run(){
f...
...System.out.println(e);}
\par
t2.start();
t3.start();
}
}
\end{lstlisting}

Test it Now


\begin{lstlisting}
Output:1
2
3
1
4
1
2
5
2
3
3
4
4
5
5
\end{lstlisting}

In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing.