Thread Join With Timeout Java with example - Java @ Desk

Saturday, March 29, 2014

Thread Join With Timeout Java with example

Thread Join With Timeout Java with example

In our last post, we understood the core basics of join() method of threads.

But the join() method has one disadvantage, it waits indefinetly for the thread to finish its execution in order to resume the joining thread.

join(long milliseconds) is more effective to use as it takes timeout as parameter. So if

Thread Execution Time > milliseconds parameter, then the thread which is waiting will resume its job after milliseconds parameter.

Look at the client below

Main Thread starts its execution
Thread-0 joins main thread with Timeout 5 seconds
But Thread-0 takes 10 seconds to get over
In this case, main thread after 5 seconds will resume its operations and move ahead.

package test;

public class ThreadJoin implements Runnable {

 @Override
 public void run() {
  try {
   System.out.println("Runnable Thread Started - "
     + Thread.currentThread().getName());
   Thread.sleep(10000);

  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("Runnable Over - "
    + Thread.currentThread().getName());
 }

 public static void main(String args[]) throws Exception {
  System.out.println("Main Started");
  Thread thread = new Thread(new ThreadJoin());

  thread.start();
  // Main thread will wait for 5 seconds and
  // then move ahead even if this thread has
  // not finished its execution
  thread.join(5000);

  System.out.println("Main Thread Over");
 }

}






No comments:

Post a Comment