Wednesday, 14 March 2018

Java Thread join() Method with Examples

           The join() method of the java.lang.Thread class is used to pause the execution of the current thread until the specified thread has finished executing.

The Thread class provides the following three overloaded join() methods:

  • join()

          This java thread join method puts the current thread on wait until the thread on which it’s called is dead. If the thread is interrupted, it throws InterruptedException.

  • join(long milisecond)

          This java thread join method is used to wait for the thread on which it’s called to be dead or wait for specified milliseconds. Since thread execution depends on OS 
implementation, it doesn’t guarantee that the current thread will wait only for given time.

  • join(long millisecond, int nanosecond)

          This java thread join method is used to wait for thread to die for given milliseconds 
plus nanoseconds.

join example,

JoinExample.java,

package com.practice;

public class JoinExample {
     
      public static void main(String[] args) {
            Thread t1 = new Thread(new MyClass(), "thread1");
            Thread t2 = new Thread(new MyClass(), "thread2");
            Thread t3 = new Thread(new MyClass(), "thread3");
         
            t1.start();
            try {
                t1.join();
            } catch (InterruptedException ex) {
            }
      
            t2.start();
            try {
                t2.join();
            } catch (InterruptedException ex) {
            }
      
            t3.start();   
            try {
                 t3.join();
            } catch (InterruptedException ie) {
            }  
      }
}
 
class MyClass implements Runnable{
 
    @Override
    public void run() {
      Thread t = Thread.currentThread();
         System.out.println("Thread started:- "+t.getName());
         try {
              Thread.sleep(1000);
         } catch (InterruptedException ex) {
              ex.printStackTrace();
         }
         System.out.println("Thread ended:- "+t.getName());
        
    }
}

Output:--Thread started:- thread1
                 Thread ended:- thread1
                 Thread started:- thread2
                 Thread ended:- thread2
                 Thread started:- thread3
                 Thread ended:- thread3



Related Post:--

No comments:

Post a Comment