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
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.
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With