How to add a Delay of a Few Seconds in Java Program

To add a delay of a few seconds in your Java Program, you can make use of the Thread.sleep() method.

Example:

package org.code2care.examples;

import java.time.LocalDateTime;

public class JavaSleepFewSecondsExample {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Sleeping every 2 seconds...");

        while(true) {
            System.out.println(LocalDateTime.now());
            Thread.sleep(2000);
        }
    }
}

Output:

Sleeping every 2 seconds...

2023-07-16T00:09:49.026082
2023-07-16T00:09:51.039858
2023-07-16T00:09:53.044546
2023-07-16T00:09:55.052225
2023-07-16T00:09:57.056692
2023-07-16T00:09:59.062389
2023-07-16T00:10:01.063584
2023-07-16T00:10:03.068924
2023-07-16T00:10:05.075274


You can also make use of the java.util.concurrent.TimeUnit class where you can pass in the time duration in seconds unlike milliseconds using Thread class.

Example:
package org.code2care.examples;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

public class JavaSleepFewSecondsExample {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Sleeping every 2 seconds...");

        while(true) {
            System.out.println(LocalDateTime.now());
            TimeUnit.SECONDS.sleep(2);
        }
    }
}

Note both these methods thorws InterruptedException which needs to be handled.


References:

Thread.sleep(): https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#sleep(long)

TimeUnit: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/TimeUnit.html

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!