Java Reference
In-Depth Information
As an alternative to defining a new subclass of
Thread
, you can implement the
Runnable
interface 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 allows only
a single base class, if you derive your class from
Thread
, it can't inherit functionality from any other class.
The
Runnable
interface declares only one method,
run()
, and this is the method that is executed when the
thread is started.
TRY IT OUT: Using the Runnable Interface
To see how this works in practice, you can write another version of the previous example. I've called this
version of the program
JumbleNames
:
import java.io.IOException;
public class JumbleNames implements Runnable {
// 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