Performs
a timed Object.wait using this time unit. The implementation for the
timedWait looks like below. It is an alternative to the wait method
of Object class.
public void timedWait(Object obj, long timeout) throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); obj.wait(ms, ns); } }
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(); } }
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
TimeUnit.SECONDS.timedWait(obj,
10) is equilant to obj.wait(10000).
Related
Posts
No comments:
Post a Comment