Search code examples
javaexceptiontimejava.util.concurrent

How to use TimeUnit in Java


I am trying to use TimeUnit in Java but it just sends me errors. This is how I wrote it:

import java.util.concurrent.TimeUnit ;

public class Anything { 
    public static void main( String[] args ) {
        System.out.println("hi");
        TimeUnit.SECONDS.sleep(6);
        System.out.println("hi");
    }
}

Solution

  • Try this as your code have many syntax errors as well as you are not handling Exception during the call of TimeUnit.SECONDS.sleep(6);, either use throws or surround this with try catch.

    import java.util.concurrent.TimeUnit ;
    
    public class Anything { 
        public static void main( String[] args ) throws InterruptedException {
            System.out.println("hi");
            TimeUnit.SECONDS.sleep(6);
            System.out.println("hi");
        }
    }