This post will discuss how to temporarily cease the execution of a Java program for a specified time.

There are two in-built mechanisms to sleep in Java.

1. Using Thread.sleep

We know that JVM allows an application to have multiple threads of execution running concurrently. To put the currently executing thread to sleep, one can use the Thread.sleep method, which takes in the total number of milliseconds to sleep.

Consider the following code, which calls the Thread.sleep method to sleep for five seconds.

Download  Run Code

Output:

Pausing for 5 seconds
Back to work…

2. Using TimeUnit

We can also use TimeUnit enumeration defined in java.util.concurrent package to perform sleep operation in Java. TimeUnit provides sleep() method, which calls Thread.sleep using the specified time unit. It has 7 constants – DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, SECONDS for convenience.

To sleep in seconds, use TimeUnit.SECONDS.

Download  Run Code

Output:

Pausing for 5 seconds
Back to work…

 
Similarly, to sleep in minutes, use TimeUnit.MINUTES.

Download Code

Output:

Pausing for 1 minute
Back to work…

 
Note that TimeUnit’s sleep() method converts time arguments into the form required by the Thread.sleep method.

That’s all about implementing sleep in Java.