What is TimeUnit.sleep() in Java?

Overview

The TimeUnit is an enum that deals with different units of time and operations related to it.

For example, it has different units of time:

  • NANOSECONDS
  • MICROSECONDS
  • MILLISECONDS
  • SECONDS
  • MINUTES
  • HOURS
  • DAYS

The sleep() method of the TimeUnit performs a Thread.sleep on the current thread using the time unit specified in the object.

This is a handy function for converting time parameters into the format required by Thread.sleep.


To learn more about Thread.sleep refer to What is Thread.sleep() in Java?

How to import the TimeUnit enum

The TimeUnit enum is defined in the java.util.concurrent package. Use the import statement below to import the TimeUnit enum:


import java.util.concurrent.TimeUnit;

Syntax


public void sleep(long timeout)

Parameters

  • long timeout: the minimum time to sleep.

The timeout parameter value relies on the unit of time chosen for the time unit object.


Return value

The method does not return anything.

Code

In the code below, we create a time unit object with SECONDS as the unit of time.

The current thread is put to sleep for the number of seconds depending on the value passed to the method sleep() of the time unit object.

import java.util.concurrent.TimeUnit;
class Main {
public static void main(String[] args) throws InterruptedException {
TimeUnit timeUnit = TimeUnit.SECONDS;
long sleepTimeInSeconds = 5;
timeUnit.sleep(sleepTimeInSeconds);
System.out.println("Slept for 5 seconds");
}
}

Free Resources