CodesJava

Easy learning with example program codes

Joining a thread in java

public final void join()

The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates.

We have to use join method when a thread wants to wait until some other thread will complete. Current thread will go in waiting state and it will be in runnable state if:

  • Second thread completes.
  • Time expires if join method is used with time constraint.
  • If waiting thread interrupted.

Example:

JoinThreadExample.java

/**
 * This program is used to show the join() method example.
 * @author codesjava
 */
class Test extends Thread{
	public void run(){
		for(int i=1;i<=5;i++){  
		   try{  
		    Thread.sleep(600);  
		   }catch(Exception e){
			   System.out.println(e);
		   }  
		   System.out.println(i);  
		  }  
	}
}
 
public class JoinThreadExample {
	public static void main(String args[]){
		//creating thread.
		Test thrd1 = new Test();
		Test thrd2 = new Test();
		Test thrd3 = new Test();
 
		thrd1.start();  
		 try{  
			 thrd1.join();  
		 }catch(Exception e){
			 System.out.println(e);
		 }  
 
		thrd2.start();
		thrd3.start();
	}
}

Output:

1
2
3
4
5
1
1
2
2
3
3
4
4
5
5

Download this example.
 
Next Topic: Daemon thread in java with example.
Previous Topic: Naming a thread in java with example.

Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status