How to pause my Java program for 2 seconds

You can find a similar post here: How to delay in Java?

Basically what says in the old post. You could use java.util.concurrent.TimeUnit

    import java.util.concurrent.TimeUnit;

    if (doAllFaceUpCardsMatch == false) {
        TimeUnit.SECONDS.sleep(2);
        concentration.flipAllCardsFaceDown();
    } else {
        concentration.makeAllFaceUpCardsInvisible();
    }

You can use:

 Thread.sleep(2000);

or

java.util.concurrent.TimeUnit.SECONDS.sleep(2);

Please note that both of these methods throw InterruptedException, which is a checked Exception, So you will have to catch that or declare in the method.

Edit: After Catching the exception, your code will look like this:

if (doAllFaceUpCardsMatch == false) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        concentration.flipAllCardsFaceDown();
} else {
        concentration.makeAllFaceUpCardsInvisible();
}

Since you are new, I would recommend learning how to do exception handling once you are little bit comfortable with java.


For those just wanting a quick hack without having to bring in a library...

public class Timing {
    public static void main(String[] args) {
            int delay = 1000; // number of milliseconds to sleep

            long start = System.currentTimeMillis();
            while(start >= System.currentTimeMillis() - delay); // do nothing

            System.out.println("Time Slept: " + Long.toString(System.currentTimeMillis() - start));
    }
}

For high precision 60fps gaming this probably isn't what you want, but perhaps some could find it useful.

Tags:

Timer

Java

Pause