Java Reference
In-Depth Information
14.1. Creating Threads
To create a thread of control, you start by creating a
THRead
object:
Thread worker = new Thread();
After a
THRead
object is created, you can configure it and then run it.
Configuring a thread involves setting its initial priority, name, and so on.
When the thread is ready to run, you invoke its
start
method. The
start
method spawns a new thread of control based on the data in the
Thread
object, then returns. Now the virtual machine invokes the new thread's
run
method, making the thread active. You can invoke
start
only once for
each threadinvoking it again results in an
IllegalThreadStateException
.
When a thread's
run
method returns, the thread has exited. You can re-
quest that a thread cease running by invoking its
interrupt
methoda re-
quest a well-written thread will always respond to. While a thread is run-
ning you can interact with it in other ways, as you shall soon see.
The standard implementation of
Thread.run
does nothing. To get a thread
that does something you must either extend
Thread
to provide a new
run
method or create a
Runnable
object and pass it to the thread's constructor.
We first discuss how to create new kinds of threads by extending
THRead
.
We describe how to use
Runnable
in the next section.
Here is a simple two-threaded program that prints the words "ping" and
"
PONG
" at different rates:
public class PingPong extends Thread {
private String word; // what word to print
private int delay; // how long to pause
public PingPong(String whatToSay, int delayTime) {
word = whatToSay;
delay = delayTime;
}