The first three were added by Java SE 6.
Although TimeUnit lets you specify any of these values in calls to methods that take a
timing argument, there is no guarantee that the system is capable of the specified resolution.
Here is an example that uses TimeUnit. The CallableDemo class, shown in the previous
section, is modified as shown next to use the second form of get( ) that takes a TimeUnit
argument.
try {
System.out.println(f.get(10, TimeUnit.MILLISECONDS));
System.out.println(f2.get(10, TimeUnit.MILLISECONDS));
System.out.println(f3.get(10, TimeUnit.MILLISECONDS));
} catch (InterruptedException exc) {
System.out.println(exc);
}
catch (ExecutionException exc) {
System.out.println(exc);
} catch (TimeoutException exc) {
System.out.println(exc);
}
In this version, no call to get( ) will wait more than 10 milliseconds.
The TimeUnit enumeration defines various methods that convert between units. These
are shown here:
long convert(long tval, TimeUnit tu)
long toMicros(long tval)
long toMillis(long tval)
long toNanos(long tval)
long toSeconds(long tval)
long toDays(long tval)
long toHours(long tval)
long toMinutes(long tval)
The convert( ) method converts tval into the specified unit and returns the result. The to
methods perform the indicated conversion and return the result. The last three methods
were added by Java SE 6.
TimeUnit also defines the following timing methods:
void sleep(long delay) throws InterruptedExecution
void timedJoin(Thread thrd, long delay) throws InterruptedExecution
void timedWait(Object obj, long delay) throws InterruptedExecution
Here, sleep( ) pauses execution for the specified delay period, which is specified in
terms of the invoking enumeration constant. It translates into a call to Thread.sleep( ).
The timedJoin( ) method is a specialized version of Thread.join( ) in which thrd pauses
for the time period specified by delay, which is described in terms of the invoking time
unit. The timedWait( ) method is a specialized version of Object.wait( ) in which obj is
waited on for the period of time specified by delay, which is described in terms of the
invoking time unit.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home