Java Reference
In-Depth Information
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 call the run() method directly, you have not created a new
thread and your program does not work as you intended.
You can define a class that is to represent a thread in two ways:
• You can define a subclass of Thread that provides a definition of the run() method that overrides
the inherited method.
• You can define your class as implementing the Runnable interface, which declares the run()
method, and then creates a Thread object in your class when you need it.
You explore the advantages of both approaches in a little more detail. You can see how deriving a subclass
of Thread works by using an example.
TRY IT OUT: Deriving a Subclass of Thread
You define a single class, TryThread , which you derive from Thread . As always, execution of the ap-
plication starts in the main() method. Here's the code:
import java.io.IOException;
public class TryThread extends Thread {
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
Search WWH ::




Custom Search