How to Add Delays or Pauses in Java
As a programmer, you may sometimes need your application to pause for a set time or until the user presses a key. You can order the thread to sleep and yield its processor time to the operating system and other programs for a set time. On the other hand, the easiest way to pause while waiting for a keystroke is just to read the keystroke and discard it. This also has the effect of pausing the program to wait for user input.
Things You'll Need
- Netbeans or another Java IDE
Open Netbeans or your favorite Java Integrated Development Environment, or IDE.
Create a new class by clicking "File" and "New Class." Name it "PauseTester."
Type "psvm" and Netbeans expands this into a valid "main" method for you.
Type the following code into the "main" method:System.out.print("I am waiting...");Thread.sleep(3000);System.out.println("DONE.");System.out.println("Press any key to end the program.");System.in.read();Two different methods are being combined here to pause the program. First, Java prints a message and sleeps for three seconds -- 3,000 milliseconds -- before printing a "DONE" message. Next, Java asks the user to press a key, and "System.in" waits until it reads a single byte of data from the keyboard. Normally, you could get the key value from "System.in," but if your goal is simply to pause, then you don't care what key is pressed.
Tips & Warnings
- Take care to split an AWT or Swing Graphical User Interface (GUI) into its own processing thread; otherwise, calling "Thread.sleep()" causes the user interface to stop responding.
- In a multithreaded application, "Thread.sleep" only pauses the thread which executes it.