Example of TimeUnit in Java

By Arvind Rai, February 18, 2013
TimeUnit belongs to the package java.util.concurrent. TimeUnit has come in java since jdk 1.5. TimeUnit playes with 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 convert method that can convert the given long value in required Time Unit. TimeUnit has timedJoin . normal join function in java, waits for a thread until that thread completes its job but timedJoin waits only up to a time and then control releases of calling thread.
TimeUnit.SECONDS.timedJoin(th, 5); 
Find the full code example.
TimeUnitTest.java
package com.concretepage;
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();
                }
            }
        }
    }
}
POSTED BY
ARVIND RAI
ARVIND RAI








©2023 concretepage.com | Privacy Policy | Contact Us