Joining a thread

join() method is used to wait for a thread to finish . This method waits until the thread on which it is called terminates. Its name comes from the concepts of the calling thread waiting until the specified thread joins it.


Syntax of join() Method

  public void join()throws InterruptedException

  public void join(long milliseconds)throws InterruptedException

Example of join() method


//example join method
class UserThread extends Thread
{
	public void run()
	{
		System.out.println("Child thread started...");
		try
		{
			for(int i=1;i<=10;i++)
			{
				System.out.println("value of i ="+i);
				Thread.sleep(1000);
			}
			System.out.println("Child thread termined...");
		}catch(InterruptedException e)
		{
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		System.out.println("Main thread started......");
		System.out.println("Now going to start user thread...");
		UserThread t=new UserThread();
		t.start();
		try
		{
			System.out.println("waiting for userthread to terminate..");
			// now main method wait till t dies
			t.join();
		}catch(InterruptedException e)
		{
			e.printStackTrace();
		}
		System.out.println("Main thread terminated.....");
	}
}
Main thread started......
Now going to start user thread...
waiting for userthread to terminate..
Child thread started...
value of i =1
value of i =2
value of i =3
value of i =4
value of i =5
value of i =6
value of i =7
value of i =8
value of i =9
value of i =10
Child thread termined...
Main thread terminated.....