Java Thread Join using join() method

In this part of tutorial we will learn how to use the join method in the Thread. Then We will create an example of Thread with the use of join method.

  • Java Join method join the next thread at the end of the current thread
  • After current thread stops execution then next thread executes.

Syntax:

public void join() throws InterruptedException
public void join(long miliseconds) throws InterruptedException

class JoinDemo extends Thread{
 public void run(){
  for(int i=1;i<=5;i++){
   try{
    Thread.sleep(500);
   }catch(Exception e){
     System.out.println(e);
   }
   System.out.println("Dinesh on Java "+i);
   }
  }
public static void main(String args[]){
 JoinDemo t1 = new JoinDemo();
 JoinDemo t2 = new JoinDemo();
 JoinDemo t3 = new JoinDemo();
 t1.start();
 try{
  t1.join();
 }catch(Exception e){
   System.out.println(e);
 }

 t2.start();
 t3.start();
 }
}

As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.
output:

Java Thread Join using join() method

//Example of join(long miliseconds) method
class JoinDemo extends Thread{
 public void run(){
  for(int i=1;i<=5;i++){
   try{
    Thread.sleep(500);
   }catch(Exception e){
     System.out.println(e);
   }
   System.out.println("Dinesh on Java "+i);
   }
  }
public static void main(String args[]){
 JoinDemo t1 = new JoinDemo();
 JoinDemo t2 = new JoinDemo();
 JoinDemo t3 = new JoinDemo();
 t1.start();
 try{
  t1.join(1500);
 }catch(Exception e){
   System.out.println(e);
 }

 t2.start();
 t3.start();
 }
}

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

Java Threads Join
Naming a thread:
The Thread class provides methods to change and get the name of a thread.

Using getName(), setName(String) and getId() method:

public String getName()//is used to return the name of a thread.
public void setName(String name)//is used to change the name of a thread.
public long getId()//is used to return the id of a thread.

class JoinDemo extends Thread{
 public void run(){
  for(int i=1;i<=5;i++){
   try{
    Thread.sleep(500);
   }catch(Exception e){
     System.out.println(e);
   }
   System.out.println("Running thread is "+Thread.currentThread().getName()+" : "+i);
   }
  }
public static void main(String args[]){
 JoinDemo t1 = new JoinDemo();
 JoinDemo t2 = new JoinDemo();
 JoinDemo t3 = new JoinDemo();
 t1.setName("Dinesh on Java");
 System.out.println("id of t1:"+t1.getId());
 System.out.println("id of t2:"+t2.getId());
 System.out.println("id of t3:"+t3.getId());
 t1.start();
 try{
  t1.join(1500);
 }catch(Exception e){
   System.out.println(e);
 }

 t2.start();
 t3.start();
 }
}

The currentThread() method:
The currentThread() method returns a reference to the currently executing thread object.
output:

Threads Join() method

<<Previous <<   || Index ||   >>Next >>

Previous
Next