javatutelearn.com

Easy Learning


Home

Search Javatutelearn.com :



join() method of thread

  • join() method ensures that currently executing thread completes its task first, then next instruction will start.
  • Suppose, there are two threads t1 and t2, and join() method is used with t1 thread. Next thread is t2. Thread t2 will start when t1 thread completes its task.

Syntax

1. public final void join()
2. public final synchronized void join(long millis) :- Thread waits for specified time or it becomes dead before specified time.
3. public final synchronized void join(long millis, int nanos):- It is similar to syntax 2, only the change is time includes both milliseconds and nanoseconds (milliseconds+nanoseconds).

Example

 public class   joinexamp  extends  Thread {
    public void  run(){
        
        for(int i=0;i<5;i++)
        {
            System.out.println("current executing thread is "+Thread.currentThread().getName());
         }
    }
    public static void  main(String args[])
    {
        joinexamp t0 = new   joinexamp();
        joinexamp t1 =  new  joinexamp();
        joinexamp t2 =  new  joinexamp();
        
        t0.start();
        t1.start();
         try  {
            t0.join();
        }
     catch  (Exception e) {
         System.out.println("Exception raised "+e);       
            }
            System.out.println("t0 is finished now");
        t2.start();
    }
}
Note:- Use join() method in try-catch block.

Output

current executing thread is Thread-1
current executing thread is Thread-1
current executing thread is Thread-0
current executing thread is Thread-1
current executing thread is Thread-1
current executing thread is Thread-1
current executing thread is Thread-0
current executing thread is Thread-0
current executing thread is Thread-0
current executing thread is Thread-0
t0 is finished now
current executing thread is Thread-2
current executing thread is Thread-2
current executing thread is Thread-2
current executing thread is Thread-2
current executing thread is Thread-2






© Copyright 2016-2024 by javatutelearn.com. All Rights Reserved.