Java Reference
In-Depth Information
When you call the
start()
method for a
Thread
object, you are calling a native code method that
causes the operating system to initiate another thread from which the
run()
method for the
Thread
object executes.
In any case, it is not important to understand exactly how this works. Just remember: always start your
thread by calling the
start()
method. If you try to call the
run()
method directly yourself, then you
will not have created a new thread and your program will not work as you intended.
There are two ways in which you can define a class that is to represent a thread. One way is to define
your class as a subclass of
Thread
and provide a definition of the method
run()
that overrides the
inherited method. The other possibility is to define your class as implementing the interface
Runnable
,
which declares the method
run()
, and then create a
Thread
object in your class when you need it. We
will look at and explore the advantages of each approach in a little more detail.
Try It Out - Deriving a Subclass of Thread
We can see how this works by using an example. We'll define a single class,
TryThread
, which we'll
derive from
Thread
. Execution starts in the method
main()
:
import java.io.IOException;
public class TryThread extends Thread {
private String firstName; // Store for first name
private String secondName; // Store for second name
private long aWhile; // Delay in milliseconds
public TryThread(String firstName, String secondName, long delay) {
this.firstName = firstName; // Store the first name
this.secondName = secondName; // Store the second name
aWhile = delay; // Store the delay
setDaemon(true); // Thread is daemon
}
public static void main(String[] args) {
// Create three threads
Thread first = new TryThread("Hopalong ", "Cassidy ", 200L);
Thread second = new TryThread("Marilyn ", "Monroe ", 300L);
Thread third = new TryThread("Slim ", "Pickens ", 500L);
System.out.println("Press Enter when you have had enough...\n");
first.start(); // Start the first thread
second.start(); // Start the second thread
third.start(); // Start the third thread
try {
System.in.read(); // Wait until Enter key pressed
System.out.println("Enter pressed...\n");
} catch (IOException e) { // Handle IO exception
System.out.println(e); // Output the exception
}