Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make java delay for a few seconds?

Tags:

java

delay

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

like image 477
user2918193 Avatar asked Apr 25 '14 02:04

user2918193


People also ask

Is there a wait command in Java?

wait() method is a part of java. lang. Object class. When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread.


2 Answers

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();
        }
like image 128
venergiac Avatar answered Oct 11 '22 19:10

venergiac


Thread.sleep() takes in the number of milliseconds to sleep, not seconds.

Sleeping for one millisecond is not noticeable. Try Thread.sleep(1000) to sleep for one second.

like image 45
Oleksi Avatar answered Oct 11 '22 19:10

Oleksi