Java TimeUnit Example

By Arvind Rai, November 15, 2023
Java TimeUnit belongs to java.util.concurrent package. TimeUnit is introduced in Java 5. TimeUnit has 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. It has convert method that can convert the given long value in required time unit. TimeUnit has timedJoin. The join function in java, waits for a thread until that thread completes its job but timedJoin waits only up to a given time and then control releases 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
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us