Java Reference
In-Depth Information
Implementing the Runnable Interface
As an alternative to defining a new subclass of
Thread
, we can implement the interface
Runnable
in a
class. You'll find that this is generally much more convenient than deriving a class from
Thread
,
because you can derive your class from a class other than
Thread
, and it can still represent a thread.
Because Java only allows a single base class, if you derive your class from
Thread
, it can't inherit
functionality from any other class. The interface
Runnable
only declares one method,
run()
, and this
is the method that will be executed when the thread is started.
Try It Out - Using the Runnable Interface
To see how this works in practice, we can write another version of the previous example. We'll call this
version of the program
JumbleNames
:
import java.io.IOException;
public class JumbleNames implements Runnable {
private String firstName; // Store for first name
private String secondName; // Store for second name
private long aWhile; // Delay in milliseconds
// Constructor
public JumbleNames(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
}
// Method where thread execution will start
public void run() {
try {
while(true) { // Loop indefinitely...
System.out.print(firstName); // Output first name
Thread.sleep(aWhile); // Wait aWhile msec.
System.out.print(secondName+"\n"); // Output second name
}
} catch(InterruptedException e) { // Handle thread interruption
System.out.println(firstName + secondName + e); // Output the exception
}
}
public static void main(String[] args) {
// Create three threads
Thread first = new Thread(new JumbleNames("Hopalong ", "Cassidy ", 200L));
Thread second = new Thread(new JumbleNames("Marilyn ", "Monroe ", 300L));
Thread third = new Thread(new JumbleNames("Slim ", "Pickens ", 500L));
// Set threads as daemon
first.setDaemon(true);
second.setDaemon(true);
third.setDaemon(true);