Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause my Java program for 2 seconds

Tags:

java

timer

pause

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?

like image 654
Ethanph89 Avatar asked Apr 19 '17 23:04

Ethanph89


People also ask

How do you make a program stop for a few seconds in Java?

Thread. sleep(5000) pause your execution for 5 sec and resume it again. If your have any code after this statement than it will executed after 5 sec of pause. OR it will execute code written after your if/else is completed.

Is there a wait command in Java?

Simply put, wait() is an instance method that's used for thread synchronization. It can be called on any object, as it's defined right on java.

How do I sleep Java?

sleep() Method: Method Whenever Thread. sleep() functions to execute, it always pauses the current thread execution. If any other thread interrupts when the thread is sleeping, then InterruptedException will be thrown.


2 Answers

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.

like image 102
Ashish Gupta Avatar answered Sep 29 '22 11:09

Ashish Gupta


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.

like image 37
Scotty Stephens Avatar answered Sep 29 '22 11:09

Scotty Stephens