Friday 20 April 2018

Join on multiple threads in java


Join() : If a thread (name it T1) calls the join method on another Thread named T2, then T1 waits for T2 to complete its execution before it continues from that point.

below is the example of thread join .

Thread 1:
package com.thread;

public class MyThread1 extends Thread {

 public void run() {

  //Thread T-2 
  MyThread2 t2 = new MyThread2();
  t2.setName("t2");
  //T2 started
  t2.start();

  try {
   //Thread T-1 wait till Thread T-2 get completed
   t2.join();
   
  } catch (InterruptedException e1) {
   e1.printStackTrace();
  }

  //Thread -1  logic
  for (int i = 0; i < 5; i++) {
   System.out.println("child Thread -1 " + Thread.currentThread().getName());
   try {
    Thread.sleep(1000);
   } catch (Exception e) {
    System.out.println(e);
   }
  }
 }
}



Thread 2:

package com.thread;

public class MyThread2 extends Thread {

 public void run() {
  
  //Thread -2 logic
  for (int i = 0; i < 5; i++) {
   System.out.println("child Thread -2 " + Thread.currentThread().getName());
   try {
    Thread.sleep(1000);
   } catch (Exception e) {
    System.out.println(e);
   }
  }
 }
}



Thread runner class:
package com.thread;

public class ThreadRun {

 //Main Thread
 public static void main(String args[]) {
  
  //Thread T-1
  MyThread1 t1 = new MyThread1();
  t1.setName("t1");
  
  try {
   //start thread T-1
   t1.start();
   //Main thread wait for T1 to complete
   t1.join();
   
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  
  //Main thread logic
  for (int i = 0; i < 5; i++) {
   System.out.println("Main Thread");
  }
 }

}



Output:
child Thread -2 t2
child Thread -2 t2
child Thread -2 t2
child Thread -2 t2
child Thread -2 t2
child Thread -1 t1
child Thread -1 t1
child Thread -1 t1
child Thread -1 t1
child Thread -1 t1
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread

No comments:

Post a Comment

Spring boot with CORS

CORS (Cross-Origin Resource Sharing) errors occur when a web application running in a browser requests a resource from a different domain or...