How to make java delay for a few seconds?

user2918193 picture user2918193 · Apr 25, 2014 · Viewed 121k times · Source

Hey all I have this code. I want to delay my program for a few seconds and display "scanning..."

Here's what I have. This compiles but doesn't delay anything

 if (i==1){

        try {
            Thread.sleep(1);
        } catch (InterruptedException ie)
        {
            System.out.println("Scanning...");
        }

    }

thanks in advance I have int i = 1 before obviously

Answer

venergiac picture venergiac · Jan 23, 2018

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

To sleep for one second or for 10 minutes

TimeUnit.MINUTES.sleep(10);

Or Thread Sleep

try        
{
    Thread.sleep(1000);
} 
catch(InterruptedException ex) 
{
    Thread.currentThread().interrupt();
}

see also the official documentation

TimeUnit.SECONDS.sleep() will call Thread.sleep. The only difference is readability and using TimeUnit is probably easier to understand for non obvious durations.

but if you want to solve your issue

        int timeToWait = 10; //second
        System.out.print("Scanning")
        try {
            for (int i=0; i<timeToWait ; i++) {
                Thread.sleep(1000);
                System.out.print(".")
            }
        } catch (InterruptedException ie)
        {
            Thread.currentThread().interrupt();
        }