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
Other People Are Reading
Things you need
- Netbeans or another Java IDE
Open Netbeans or your favourite 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...");
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 "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 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.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for