Main Tutorials

Java – How to delay few seconds

In Java, we can use TimeUnit.SECONDS.sleep() or Thread.sleep() to delay few seconds.

1. TimeUnit

JavaDelayExample.java

package com.mkyong;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class JavaDelayExample {

    public static void main(String[] args) {

        try {

            System.out.println("Start..." + new Date());
            // delay 5 seconds
            TimeUnit.SECONDS.sleep(5);
            System.out.println("End..." + new Date());

            // delay 0.5 second
            //TimeUnit.MICROSECONDS.sleep(500);

			// delay 1 minute
            //TimeUnit.MINUTES.sleep(1);
			
        } catch (InterruptedException e) {
            System.err.format("IOException: %s%n", e);
        }


    }

}

output


Start...Mon Apr 08 21:42:55 SRET 2019
End...Mon Apr 08 21:43:00 SRET 2019

2. Thread.sleep

JavaDelayExample2.java

package com.mkyong;

import java.util.Date;

public class JavaDelayExample2 {

    public static void main(String[] args) {

        try {

            System.out.println("Start..." + new Date());
            // delay 5 seconds
            Thread.sleep(5000);
            System.out.println("End..." + new Date());

        } catch (InterruptedException e) {
            System.err.format("IOException: %s%n", e);
        }


    }

}

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
A-a-Ron
4 years ago

This was helpful, thank you very much. But (I say this mostly as a sanity-check on myself not to correct you, pls pls tell me if I’m wrong), in example 1), “TimeUnit.MICROSECONDS.sleep(500)” stalls for 0.0005 seconds, not 0.5s; that’s “MILLISECONDS”.

Dr. Mitch
3 years ago
Reply to  A-a-Ron

stop

Kuchi
8 years ago

How about:
TimeUnit.SECONDS.sleep(5);
It’s essentially the same but is nicer to read. (My opinion)

Dr. Mitch
3 years ago

I am in this discussoio0n

jayant kumar
5 years ago

Thanks sir, This help me a lot to resolve my issue.

Stas Miroshnik
8 years ago

how to delay many seconds ? ))

badboy
5 years ago
Reply to  Stas Miroshnik

5 sec