Advance Java

Learn New things from Rixosys

join and sleep Method

Thread join() method in Java with example

The join() method is used to hold the execution of currently running thread until the specified thread is dead(finished execution). In this tutorial we will discuss the purpose and use of join() method with examples.

Why we use join() method?

In normal circumstances we generally have more than one thread, thread scheduler schedules the threads, which does not guarantee the order of execution of threads.
For example lets have a look at the following code:

Without using join()

Here we have three threads th1, th2 and th3. Even though we have started the threads in a sequential manner the thread scheduler does not start and end them in the specified order. Everytime you run this code, you may get a different result each time. So the question is: How can we make sure that the threads executes in a particular order. The Answer is: By using join() method appropriately.

public class JoinExample2 {
   public static void main(String[] args) {
      Thread th1 = new Thread(new MyClass2(), "th1");
      Thread th2 = new Thread(new MyClass2(), "th2");
      Thread th3 = new Thread(new MyClass2(), "th3");
         
      th1.start();
      th2.start();        
      th3.start();
   }
}
 
class MyClass2 implements Runnable{
 
    @Override
    public void run() {
    	Thread t = Thread.currentThread();
        System.out.println("Thread started: "+t.getName());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
        System.out.println("Thread ended: "+t.getName());    
    }
}

Output:

Thread started: th1
Thread started: th3
Thread started: th2
Thread ended: th1
Thread ended: th3
Thread ended: th2

Lets have a look at the another code where we are using the join() method.

The same example with join()

Lets say our requirement is to execute them in the order of first, second and third. We can do so by using join() method appropriately.

public class JoinExample {
   public static void main(String[] args) {
      Thread th1 = new Thread(new MyClass(), "th1");
      Thread th2 = new Thread(new MyClass(), "th2");
      Thread th3 = new Thread(new MyClass(), "th3");
         
      // Start first thread immediately
      th1.start();
         
      /* Start second thread(th2) once first thread(th1) 
       * is dead
       */
      try {
          th1.join();
      } catch (InterruptedException ie) {
          ie.printStackTrace();
        }
      th2.start();
         
      /* Start third thread(th3) once second thread(th2) 
       * is dead
       */
      try {
          th2.join();
      } catch (InterruptedException ie) {
           ie.printStackTrace();
        }
      th3.start();
         
      // Displaying a message once third thread is dead
      try {
          th3.join();
      } catch (InterruptedException ie) {
            ie.printStackTrace();
        }  
      System.out.println("All three threads have finished execution");
   }
}
 
class MyClass implements Runnable{
 
    @Override
    public void run() {
    	Thread t = Thread.currentThread();
        System.out.println("Thread started: "+t.getName());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
        System.out.println("Thread ended: "+t.getName());
        
    }
}

Output:

Thread started: th1
Thread ended: th1
Thread started: th2
Thread ended: th2
Thread started: th3
Thread ended: th3
All three threads have finished execution

Thread.sleep in Java

Thread.sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can’t be negative, else it throws IllegalArgumentException.

There is another overloaded method sleep(long millis, int nanos) that can be used to pause the execution of current thread for specified milliseconds and nanoseconds. The allowed nano second value is between 0 and 999999.

Java Thread Sleep Example

Here is a simple program where Thread.sleep() is used to pause the main thread execution for 2 seconds.

ThreadSleep.java


package com.journaldev.threads;

public class ThreadSleep {

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(2000);
        System.out.println("Sleep time in ms = "+(System.currentTimeMillis()-start));
        
    }

}

If you will run the above program, you will notice that the thread sleep time it prints is slightly greater than 2000. This is caused by how thread sleep works and operating system specific implementation of thread scheduler.

Java Thread Sleep important points

  1. It always pause the current thread execution.
  2. The actual time thread sleeps before waking up and start execution depends on system timers and schedulers. For a quiet system, the actual time for sleep is near to the specified sleep time but for a busy system it will be little bit more.
  3. Thread sleep doesn’t lose any monitors or locks current thread has acquired.
  4. Any other thread can interrupt the current thread in sleep, in that case InterruptedException is thrown.

How Thread Sleep Works

Thread.sleep() interacts with the thread scheduler to put the current thread in wait state for specified period of time. Once the wait time is over, thread state is changed to runnable state and wait for the CPU for further execution. So the actual time that current thread sleep depends on the thread scheduler that is part of operating system.