Showing posts with label join(). Show all posts
Showing posts with label join(). Show all posts

Thread join()

 
Basically Thread.join() method allows one thread to wait for the completion of another thread. Suppose if a Thread "A" is running and when we call A.join(), causes the current thread to halt its execution until A thread terminates or complete its process. By join we can make the current thread to wait for the time as same as sleep() method. Where as timing depends on the Operating System and its not on the time which we can specify. Apart from waiting time join can be interrupt by InterruptedException as same as in sleep in method. 

There are 3 types of join() methods in Java Thread class and they are 

void join()
- Waits for the current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

void join(long ms)
- Waits at most (ms) milliseconds for current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

void join(long ms, int ns)
- Waits at most (ms) milliseconds and (ms) nanoseconds for current thread to terminate or to finish its process.
- Throws InterruptedException if another thread has interrupted the current thread.
- Returns nothing.

Lets see simple example in Java Thread to use join() method and how its works.


public class ThreadJoinTest implements Runnable {
 
 @Override
 public void run() {
  try {
   System.out.println(Thread.currentThread().getName());
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) {
  ThreadJoinTest obj = new ThreadJoinTest();
  for(int i=0;i<10;i++){
   Thread t = new Thread(obj);
   t.start();
   try {
    t.join();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
}


OUTPUT:


Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-7
Thread-8
Thread-9


If we seen above program we have used t.join() for each Thread which we have created. Since join we have used it makes other thread to wait until current thread to complete. This program will work similar to normal java code without multi-threading implementation. Please try with same code by removing t.join() where we can see normal multi-threading implementation on same Object.

OUTPUT: ( By removing t.join() )


Thread-1
Thread-3
Thread-5
Thread-7
Thread-9
Thread-0
Thread-2
Thread-4
Thread-6
Thread-8