How to pause my Java program for 2 seconds
Asked Answered
P

5

17

I'm new to Java and making a small game for practice.

if (doAllFaceUpCardsMatch == false) {
        //run pause here//
        concentration.flipAllCardsFaceDown();
} else {
        concentration.makeAllFaceUpCardsInvisible();
}

I want to pause the game for two seconds here before it does

concentration.flipAllCardsFaceDown();

How would I go about pausing it?

Postman answered 19/4, 2017 at 23:13 Comment(5)
Possible duplicate of How to delay in Java?Clarkin
Thread.sleep would be the obvious choice, however, if you're using a GUI like Swing or JavaFX, you shouldn't do this from within the context of their dispatching threads, that would be really, really bad. Most UI frameworks will have their own defined mechanisms for doing this, but we don't have that informationBuilt
When I do Thread.sleep() I get: "error: unreported exception InterruptedException; must be caught or declared to be thrown Thread.sleep(2000);" when compilingPostman
@Postman well, the compiler is telling you exactly what you have to do: catch the InterruptedException, or declare it to be thrown.Zlatoust
Incidentally, don't explicitly compare to true and false.Stuckey
C
29

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.

Chasitychasm answered 19/4, 2017 at 23:19 Comment(1)
Thanks for the help! Like I said, I'm new to Java (and most programming in general)- how would I catch the Exception?Postman
S
2

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.

Sanitarium answered 11/5, 2018 at 17:21 Comment(2)
This has a wasteful high CPU usage.Coussoule
This is what I needed. The popular Swing Timer approach doesn't work because the main thread continues on while the Timer is executing.Notogaea
P
1

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();
    }
Patel answered 19/4, 2017 at 23:19 Comment(0)
I
0

You can use Thread.currentThread().sleep(2000) to pause the current thread for 2 seconds (2000 milleseconds). You should surround this with a try/catch in case of InterruptedExceptions.

Incriminate answered 19/4, 2017 at 23:23 Comment(0)
K
0

Another very simple way is creating the following method:

public static void pause(long timeInMilliSeconds) {

    long timestamp = System.currentTimeMillis();


    do {

    } while (System.currentTimeMillis() < timestamp + timeInMilliSeconds);

}
Knighterrant answered 10/4, 2020 at 1:34 Comment(2)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Brahmanism
I guess that's ok for anyone who knows what a method is, and how to invoke it. If one doesn't know, this one shouldn't be here copying and pasting code, but doing some basic Java course. There's a very straight line between giving a helping hand and chainning a soul.Knighterrant

© 2022 - 2024 — McMap. All rights reserved.