TimeUnit belongs to the java.util.concurrent package. TimeUnit has arrived in java since jdk 1.5. TimeUnit plays with the unit of time. TimeUnit has many units like DAYS, MINUTES, SECONDS etc.
TimeUnit tu=TimeUnit.DAYS;
TimeUnit is an enum. When we call TimeUnit.DAYS or any other unit, it returns TimeUnit. TimeUnit has a conversion method that can convert the given long value into the unit of time required. TimeUnit has timedJoin. Normal join function in java, wait for a thread until the thread finishes its work, but timedJoin waits only until a moment and then the control of the thread versions of call.
TimeUnit.SECONDS.timedJoin(th, 5);
This is a complete code example.
TimeUnitTest.java
package com.GilbertoQuintero;
import java.util.concurrent.TimeUnit;
public class TimeUnitTest {
public static void main(String... args) throws InterruptedException{
TimeUnit tu=TimeUnit.DAYS;
long noOfDays=tu.convert(48,TimeUnit.HOURS);
System.out.println("noOfDays:"+noOfDays);
TimeUnit.SECONDS.sleep(2);
Thread th=new Thread( new TimeUnitTest().new RunnableThread());
th.start();
TimeUnit.SECONDS.timedJoin(th, 5);
System.out.println("done");
}
//runnable thread
class RunnableThread implements Runnable {
@Override
public void run() {
int cnt = 0;
for (; cnt < 5;cnt++ ) {
System.out.println("run:" + cnt);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}