How to Add Delays or Pauses in Java

By Amber D. Walker

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

Step 1

Open Netbeans or your favorite Java Integrated Development Environment, or IDE.

Step 2

Create a new class by clicking "File" and "New Class." Name it "PauseTester."

Step 3

Type "psvm" and Netbeans expands this into a valid "main" method for you.

Step 4

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.");;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 "" waits until it reads a single byte of data from the keyboard. Normally, you could get the key value from "," but if your goal is simply to pause, then you don't care what key is pressed.

Step 5

Click "Run."

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.

References & Resources