TimeUnit Class in Java with Examples
TimeUnit is an Enum available in java.util.concurrent package. TimeUnit as the name implies deals with Time units. TimeUnit provides time representation at a given unit of granularity. It makes available methods to convert time across time units. TimeUnit is useful to know how a given time should be interpreted that is which time unit should be considered. Minute differences between time durations such as in microseconds and nanoseconds can be figured out using TimeUnit. It is used to perform timing and delay operations.
It supports nanoseconds, microseconds, milliseconds, seconds, minutes, hours, and days units. For these units, TimeUnit specifies corresponding enum constants:
- Nanoseconds: One thousandth of a microsecond
- Microseconds: One thousandth of a millisecond
- Milliseconds: One thousandth of a second
- Seconds: Oone second
- Minutes: Sixty seconds
- Hours: Sixty minutes
- Days: Twenty four hours
96 Hours = 4 Days = 5760 Minutes 5760 Minutes = 345600000000 Microseconds 345600000000 Microseconds = 345600 Seconds TimeUnit object type: MINUTES
TimeUnit Example Now, thread will run for 5 seconds NANOSECONDS : 86400000000000 MICROSECONDS : 86400000000 MILLISECONDS : 86400000 SECONDS : 86400 Thread Execution Paused Resuming Thread Execution... MINUTES : 1440 HOURS : 24 DAYS : 1
Utility methods available in TimeUnit:
Methods Description long convert() Converts the time duration inputted with its unit to the required unit. long toDays() Converts the time duration to Days. long toHours() Converts the time duration to Hours. long toMicros() Converts the time duration to Microseconds. long toMillis() Converts the time duration to Milliseconds. long toMinutes() Converts the time duration to Minutes. long toNanos() Converts the time duration to Nanoseconds. long toSeconds() Converts the time duration to Seconds. static TimeUnit valueOf() Returns the enum constant of the type with the specified name. static TimeUnit  values() Returns an array containing the enum constants. void sleep() Performs a Thread.sleep using this time unit. Pause for given TimeUnit. void timedWait() Performs a timed Object.wait using this time unit. Wait for the given time unit to execute. void timedJoin() Performs a timed Thread.join using this time unit. Thread is provided to do work for a given time duration only.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.