How to Add Delays or Pauses in Java

Written by amber d. walker
  • Share
  • Tweet
  • Share
  • Email

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.

Skill level:
Moderately Easy

Things you need

  • Netbeans or another Java IDE

Show MoreHide


  1. 1

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

  2. 2

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

  3. 3

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

  4. 4

    Type the following code into the "main" method:

    System.out.print("I am waiting...");



    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.

  5. 5

    Click "Run."

Tips and 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.

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.