How to make java delay for a few seconds?

北城以北 提交于 2019-12-23 07:14:35

问题


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


回答1:


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();
        }



回答2:


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.




回答3:


You have System.out.println("Scanning...") in a catch block. Do you want to put that in try?




回答4:


This is in a mouseEvent btw

If this is in a Swing GUI, then get rid of all calls to Thread.sleep(...) as doing so can put the entire GUI to sleep rendering it useless. Instead use a Swing Timer to produce any delays in the GUI while letting it still update its graphics.

You'll also want to avoid System.out.println(...) calls, except when debugging, and instead display user notifications in the GUI itself, perhaps in a status JLabel or as a message dialog.




回答5:


Java:

For calculating times we use this method:

import java.text.SimpleDateFormat;
import java.util.Calendar;


    public static String getCurrentTime() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    return sdf.format(cal.getTime());
}

Second:

import java.util.concurrent.TimeUnit;

System.out.println("Start delay of 10 seconds, Time is: " + getCurrentTime());
TimeUnit.SECONDS.sleep(10);
System.out.println("And delay of 10 seconds, Time is: " + getCurrentTime());

Output:

Start delay of 10 seconds, Time is: 14:19:08

And delay of 10 seconds, Time is: 14:19:18

Minutes:

import java.util.concurrent.TimeUnit;

System.out.println("Start delay of 1 Minute, Time is: " + getCurrentTime());
TimeUnit.MINUTES.sleep(1);
System.out.println("And delay of 1 Minute, Time is: " + getCurrentTime());

Output:

Start delay of 1 Minute, Time is: 14:21:20

And delay of 1 Minute, Time is: 14:22:20

Milliseconds:

import java.util.concurrent.TimeUnit;

System.out.println("Start delay of 2000 milliseconds, Time is: " +getCurrentTime());
TimeUnit.MILLISECONDS.sleep(2000);
System.out.println("And delay of 2000 milliseconds, Time is: " + getCurrentTime());

Output:

Start delay of 2000 milliseconds, Time is: 14:23:44

And delay of 2000 milliseconds, Time is: 14:23:46

Or:

Thread.sleep(1000); //milliseconds



回答6:


As per java documentation definition of Thread.sleep is :

Thread.sleep(t);
where t => time in millisecons to sleep

If you want to sleep for 1 second you should have :

Thread.sleep(1000);



回答7:


A couple problems, you aren't delaying by much (.sleep is milliseconds, not seconds), and you're attempting to print in your catch statement. Your code should look more like:

if (i==1) {
    try {
        System.out.println("Scanning...");
        Thread.sleep(1000); // 1 second
    } catch (InterruptedException ex) {
        // handle error
    }
}



回答8:


move the System.out statement to finally block.




回答9:


Use Thread.sleep(2000); //2000 for 2 seconds




回答10:


You need to use the Thread.sleep() method.

This is used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can’t be negative, else it throws IllegalArgumentException.

FYI (Summary taken from here)

Java Thread Sleep important points

  • It always pause the current thread execution.
  • Thread sleep doesn’t lose any monitors or locks current thread has acquired.
  • Any other thread can interrupt the current thread in sleep, in that case InterruptedException is thrown.



回答11:


waiting for some(like 10) seconds your compiler to use this static class method
TimeUnit.SECONDS.sleep(10);
it's including in java.util.concurrent.TimeUnit libery



来源:https://stackoverflow.com/questions/23283041/how-to-make-java-delay-for-a-few-seconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!