Java Reference
In-Depth Information
Writing a Threaded Program
Threads are implemented in Java with the Thread class in the java.lang package.
The simplest use of threads is to make a program pause in execution and stay idle during
that time. To do this, call the Thread class method sleep( long ) with the number of mil-
liseconds to pause as the only argument.
This method throws an exception, InterruptedException , whenever the paused thread
has been interrupted for some reason. (One possible reason: The user closes the program
while it is sleeping.)
The following statements stop a program in its tracks for three seconds:
try {
Thread.sleep(3000);
catch (InterruptedException ie) {
// do nothing
}
The catch block does nothing, which is typical when you're using sleep() .
One way to use threads is to put all the time-consuming behavior into its own class.
A thread can be created in two ways: by subclassing the Thread class or implementing
the Runnable interface in another class. Both belong to the java.lang package, so no
import statement is necessary to refer to them.
Because the Thread class implements Runnable , both techniques result in objects that
start and stop threads in the same manner.
To implement the Runnable interface, add the keyword implements to the class declara-
tion followed by the name of the interface, as in the following example:
public class StockTicker implements Runnable {
public void run() {
// ...
}
}
When a class implements an interface, it must include all methods of that interface. The
Runnable interface contains only one method, run() .
The first step in creating a thread is to create a reference to an object of the Thread class:
Thread runner;
This statement creates a reference to a thread, but no Thread object has been assigned to
it yet. Threads are created by calling the constructor Thread( Object ) with the threaded
Search WWH ::




Custom Search