ptg7068951
266 HOUR 19:Creating a Threaded Program
Slowing Down a Program
TheThreadclass has a sleep()method that you can call in any program
that should stop running for a short period of time. You often see this tech-
nique used in a program that features animation because it prevents images
from being displayed faster than the Java interpreter can handle them.
To use the sleep()method, call Thread.sleep()with the number of mil-
liseconds to pause, as in the following statement:
Thread.sleep(5000);
The preceding statement causes the Java interpreter to pause for five sec-
onds before doing anything else. If for some reason the interpreter can’t
pause that long, an InterruptedExceptionis thrown by the sleep()
method.
Because this exception might be thrown, you must deal with it in some
manner when using the sleep()method. One way to do this is to place
the Thread.sleep()statement inside a try-catchblock:
try {
Thread.sleep(5000);
} catch(InterruptedException e) {
// wake up early
}
When you want a Java program to handle more than one thing at a time,
you must organize the program into threads. Your program can have as
many threads as needed, and they all can run simultaneously without
affecting each other.
Creating a Thread
A Java class that can be run as a thread is referred to as a runnable(orthread-
ed)class. Although you can use threads to pause a program’s execution for a
few seconds, programmers often use them for the opposite reason—to speed
up a program. If you put time-consuming tasks in their own threads, the rest
of the program runs more quickly. This often is used to prevent a task from
slowing down the responsiveness of a program’s graphical user interface
(GUI).
For example, if you have written an applicationthat loads stock market
price data from disk and compiles statistics, the most time-consuming task
is to load the data from disk. If threads are not used in the application, the