Sleep in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Main { public static void main(String[] args) { System.out.println("Pausing for 5 seconds"); // To sleep for five seconds try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Back to work…"); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.concurrent.TimeUnit; class Main { public static void main(String[] args) { System.out.println("Pausing for 5 seconds"); // To sleep for five seconds try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Back to work…"); } } |
Output:
Pausing for 5 seconds
Back to work…
Similarly, to sleep in minutes, use TimeUnit.MINUTES.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.concurrent.TimeUnit; class Main { public static void main(String[] args) { System.out.println("Pausing for 1 minute"); // To sleep for one minute try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Back to work…"); } } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)