• August 29, 2014
  • Core Java
  • Comments Off on Joining a thread in java

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.

Example:

JoinThreadExample.java

/**
 * This program is used to show the join() method example.
 * @author javawithease
 */
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.

Related Topics:

Multithreading in java.
Thread life cycle in java.
Way of creating thread in java.
Commonly used methods of Thread class.
Thread scheduling in java with example.
Thread priority in java with example.
Naming a thread in java with example.
Joining a thread in java with example.
Daemon thread in java with example.
Can we start a thread twice?
Can we call run method directly?
Difference between Thread.yield() and Thread.sleep() methods.
Deadlock in java with example.
Starvation in java with example.
Inter-thread communication in java with example.
Synchronization in java with example.
Synchronized method in java with example.
Static synchronization in java with example.
Synchronized block in java with example.

 


Comments are closed.