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.


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap