How to pause the code execution in Java

Sometimes you want to pause the execution of your Java code for a fixed number of milliseconds or seconds until another task is finished. There are multiple ways to achieve this.

Thread.sleep() method

The quickest way to stop the code execution in Java is to instruct the current thread to sleep for a certain amount of time. This is done by calling the Thread.sleep() static method:

try {
    System.out.printf("Start Time: %s\n", LocalTime.now());
    Thread.sleep(2 * 1000); // Wait for 2 seconds
    System.out.printf("End Time: %s\n", LocalTime.now());
} catch (InterruptedException e) {
    e.printStackTrace();
}

The code above stops the execution of the current thread for 2 seconds (or 2,000 milliseconds) using the Thread.sleep() method.

Also, notice the try...catch block to handle InterruptedException. It is used to catch the exception when another thread interrupts the sleeping thread.

This exception handling is necessary for a multi-threaded environment where multiple threads are running in parallel to perform different tasks.

TimeUnit.SECONDS.sleep() method

For better readability, you can also use the TimeUnit.SECONDS.sleep() method to pause a Java program for a specific number of seconds as shown below:

try {
    System.out.printf("Start Time: %s\n", LocalTime.now());
    TimeUnit.SECONDS.sleep(2);  // Wait 2 seconds
    System.out.printf("End Time: %s\n", LocalTime.now());
} catch (InterruptedException e) {
    e.printStackTrace();
}

Under the hood, the TimeUnit.SECONDS.sleep() method also calls the Thread.sleep() method. The only difference is readability that makes the code easier to understand for unclear durations.

The TimeUnit is not just limited to seconds. It also provides methods for other time units such as nanoseconds, microseconds, milliseconds, minutes, hours, and days:

// Wait 500 nanoseconds
TimeUnit.NANOSECONDS.sleep(500);

// Wait 5000 microseconds
TimeUnit.MICROSECONDS.sleep(5000);

// Wait 500 milliseconds
TimeUnit.MILLISECONDS.sleep(500);

// Wait 5 minutes
TimeUnit.MINUTES.sleep(5);

// Wait 2 hours
TimeUnit.HOURS.sleep(2);

// Wait 1 day
TimeUnit.DAYS.sleep(1);

ScheduledExecutorService interface

The sleep times are inaccurate with Thread.sleep() when you use smaller time increments like nanoseconds, microseconds, or milliseconds. This is especially true when used inside a loop.

For every iteration of the loop, the sleep time will drift slightly due to other code execution and become completely imprecise after some iterations.

For more robust and precise code execution delays, you should use the ScheduledExecutorService interface instead. This interface can schedule commands to run after a given delay or at a fixed time interval.

For example, to run the timer() method after a fixed delay, you use the schedule() method:

public class Runner {

    public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        // Execute timer after 2 seconds
        service.schedule(Runner::timer, 2, TimeUnit.SECONDS);
    }

    public static void timer() {
        System.out.println("Current time: " + LocalTime.now());
    }
}

Similarly, to call the method timer() every second, you should use the scheduleAtFixedRate() method as shown below:

public class Runner {

    public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        // Execute timer every second
        service.scheduleAtFixedRate(Runner::timer, 0, 1, TimeUnit.SECONDS);
    }

    public static void timer() {
        System.out.println("Current time: " + LocalTime.now());
    }
}

Here is a an example output of the above code:

Current time: 08:48:11.350034
Current time: 08:48:12.335319
Current time: 08:48:13.337250
Current time: 08:48:14.334107
Current time: 08:48:15.338532
Current time: 08:48:16.336175
...

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.