Friday 7 March 2014

TimeUnit : timedJoin

public void timedJoin(Thread thread,long timeout)throws InterruptedException
Performs a timed Thread.join using this time unit. This is a convenience method that converts time arguments into the form required by the Thread.join method. It is equivalent to the join() of Thread class.

Example
public class SimpleObject {

}

import java.util.concurrent.TimeUnit;
 
public class TimeUnitEx extends Thread{
 SimpleObject obj;

 public void run(){
  synchronized(obj){
   try{
    Thread t1 = Thread.currentThread();
    System.out.println(t1.getName() +" About to wait for 10 seconds");
    TimeUnit.SECONDS.timedWait(obj, 10);
    System.out.println(t1.getName() +" wait completed");
   }
   catch(InterruptedException e){
   }
  }
 }

 TimeUnitEx(SimpleObject obj){
  this.obj = obj;
 }

 public static void main(String args[])throws Exception{
  SimpleObject obj1 = new SimpleObject();
  TimeUnitEx t1 = new TimeUnitEx(obj1);
  TimeUnitEx t2 = new TimeUnitEx(obj1);

  t1.start();
  t2.start();

  TimeUnit.SECONDS.timedJoin(t1, 11);
  TimeUnit.SECONDS.timedJoin(t2, 11);
  System.out.println("Threads finished with Execution");
 }
}
  
Output
Thread-0 About to wait for 10 seconds
Thread-1 About to wait for 10 seconds
Thread-0 wait completed
Thread-1 wait completed
Threads finished with Execution



TimeUnit timedWait                                                 Thread Pools                                                 Home

No comments:

Post a Comment