Join() method - ensure all threads that started from main must end in order in which they started and also main should end in last. Types of join() method in java


Contents of page :
  • 10 salient features of join() method >
  • Full Program to show usage of join() method>
  • Let’s discuss waiting time in detail :
  • Let’s create a program to use join(long millis) >



Interviewers tend to know interviewees knowledge about Thread methods. So this is time to prove your point by answering correctly. We can use join() method to ensure all threads that started from main must end in order in which they started and also main should end in last.In other words waits for this thread to die.
Calling join() method internally calls join(0);

10 salient features of join() method >

  • Definition : join() We can use join() method to ensure all threads that started from main must end in order in which they started and also main should end in last.In other words waits for thread to die on which thread has been called.

  • Exception : join() method throws InterruptedException, in our case we have thrown exception.

  • instance method : join() is a instance method, hence we need to have thread  instance for calling this method.

  • Thread state : when join() method is called on thread it goes from running to waiting state. And wait for thread to die.

  • Not a native method : implementation of join() method is provided in java.lang.Thread class.
Let’s see definition of join() method as given in java.lang.Thread -
public final void join() throws InterruptedException;

  • synchronized block : thread need not to to acquire object lock before calling join() method i.e. join() method can be called from outside synchronized block.

  • Waiting time : join() method have got few options.
    1. join() : Waits for this thread to die.  
public final void join() throws InterruptedException;
This method internally calls join(0). And timeout of 0 means to wait forever;

    1. join(long millis) - Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
public static native void sleep(long millis) throws InterruptedException;

    1. join(long millis, int nanos) - Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.
public static native void sleep(long millis,int nanos) throws InterruptedException;



  • Belongs to which class : join() method belongs to java.lang.Thread class.



To achieve we are going to create 2 threads on Runnable Object, create for loop in run() method and start  both threads. After starting each Thread call join() method on them to ensure they end in order in which they has started.

Full Program to show usage of join() method>
class MyRunnable implements Runnable{
   public void run(){
      System.out.println("in run() method");
          for(int i=0;i<5;i++){
                 System.out.println("i="+i+" ,ThreadName="+Thread.currentThread().getName());
          }         
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
   public static void main(String...args) throws InterruptedException{
          System.out.println("In main() method");
          MyRunnable runnable=new MyRunnable();
          Thread thread1=new Thread(runnable);
          Thread thread2=new Thread(runnable);

          thread1.start();
          thread1.join();

          thread2.start();
          thread2.join();

          System.out.println("end main() method");
   }
}
/*OUTPUT
In main() method
in run() method
i=0 ,ThreadName=Thread-0
i=1 ,ThreadName=Thread-0
i=2 ,ThreadName=Thread-0
i=3 ,ThreadName=Thread-0
i=4 ,ThreadName=Thread-0
in run() method
i=0 ,ThreadName=Thread-1
i=1 ,ThreadName=Thread-1
i=2 ,ThreadName=Thread-1
i=3 ,ThreadName=Thread-1
i=4 ,ThreadName=Thread-1
end main() method
*/
If we note output, all threads ended in order in which they were called and main thread has ended last.

First, main thread was called, it started Thread1 and then we called join() method on Thread1, once Thread1 ended main thread started Thread2 and we called join() method on Thread2, once Thread2 ended main thread also ended.
In short - calling thread1.join()  made main thread to wait until Thread-1 dies.


Let’s discuss waiting time in detail : join() method have got few options.
    1. join() : Waits for this thread to die.  
public final void join() throws InterruptedException;
This method internally calls join(0). And timeout of 0 means to wait forever;

    1. join(long millis) - Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
public static native void join(long millis) throws InterruptedException;

    1. join(long millis, int nanos) - Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.
public static native void join(long millis,int nanos) throws InterruptedException;


Let’s create a program to use join(long millis) >
First, join(1000) will be called on Thread-1, but once 1000 millisec are up, main thread can resume and start thread2 (main thread won’t wait for Thread-1 to die).
class MyRunnable implements Runnable{
   public void run(){
          System.out.println("in run() method");
          for(int i=0;i<5;i++){
                 try {
                       Thread.sleep(500);
                 } catch (InterruptedException e) {
                       e.printStackTrace();
                 }
                 System.out.println("i="+i+" ,ThreadName="+Thread.currentThread().getName());
          }         
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
   public static void main(String...args) throws InterruptedException{
          System.out.println("In main() method");
          MyRunnable runnable=new MyRunnable();
          Thread thread1=new Thread(runnable);
          Thread thread2=new Thread(runnable);
          thread1.start();
          thread1.join(1000);  //once 1000 millisec are up, main thread can resume and start thread2.
          thread2.start();
          thread2.join();
          System.out.println("end main() method");
   }
}
/*OUTPUT
In main() method
in run() method
i=0 ,ThreadName=Thread-0
i=1 ,ThreadName=Thread-0
in run() method
i=2 ,ThreadName=Thread-0
i=0 ,ThreadName=Thread-1
i=1 ,ThreadName=Thread-1
i=3 ,ThreadName=Thread-0
i=2 ,ThreadName=Thread-1
i=4 ,ThreadName=Thread-0
i=3 ,ThreadName=Thread-1
i=4 ,ThreadName=Thread-1
end main() method
*/





RELATED LINKS>

DeadLock and its detection >

Deadlock in multithreading - program to form DeadLock, solving DeadLock, measures to avoid Deadlock.


VisualVM - Thread dumps - Generating and analyzing Thread Dumps using VisualVM - step by step detail to setup VisualVM with screenshots


JSTACK - Thread dumps - Generating and analyzing Thread Dumps using JSATCK - step by step detail to setup JSTACK with screenshots


Reason why suspend() and resume() methods are deprecated and Deadlock prone

destroy() method in java - usage, reason why destroy() method is deprecated and Deadlock prone.




Important Thread methods (salient features, usage with programs)>

Join() method - ensure all threads that started from main must end in order in which they started and also main should end in last. Types of join() method-10 salient features of join

Sleep() method in threads - 10 key features with programs

Yield() method in threads - 8 key features with programs

Wait() and notify() methods- Definition, 8 key features, solving consumer producer problem with & without these methods and consequences of not using wait() and notify() methods.

Daemon threads - 12 salient features of Daemon Thread

2 alternate ways to stop thread, as stop() method is deprecated

Using Suspend and resume method in threads



Interviews >

THREADS - Top 80 interview questions and answers (detailed explanation with programs) Set-1 >  Q1- Q60

THREADS - Top 80 interview questions and answers, important interview OUTPUT questions and answers, Set-2 > Q61- Q80





No comments:

Post a Comment