14.2. Using Runnable
Threads abstract the concept of a workeran entity that gets something done. The work done by a thread is
packaged up in its run method. When you need to get some work done, you need both a worker and the
workthe Runnable interface abstracts the concept of work and allows that work to be associated with a
workerthe thread. The Runnable interface declares a single method:
public void run();
The THRead class itself implements the Runnable interface because a thread can also define a unit of
work.
You have seen that Thread can be extended to provide specific computation for a thread, but this approach
is awkward in many cases. First, class extension is single inheritanceif you extend a class to make it runnable
in a thread, you cannot extend any other class, even if you need to. Also, if your class needs only to be
runnable, inheriting all the overhead of Thread is more than you need.
Implementing Runnable is easier in many cases. You can execute a Runnable object in its own thread by
passing it to a Thread constructor. If a Thread object is constructed with a Runnable object, the
implementation of THRead.run will invoke the runnable object's run method.
Here is a Runnable version of the PingPong class. If you compare the versions, you will see that they
look almost identical. The major differences are in the supertype (implementing Runnable versus extending
Thread) and in main.
class RunPingPong implements Runnable {
private String word; // what word to print
private int delay; // how long to pause
RunPingPong(String whatToSay, int delayTime) {
word = whatToSay;
delay = delayTime;
}
public void run() {
try {
for (;;) {
System.out.print(word + " ");
Thread.sleep(delay); // wait until next time
}
} catch (InterruptedException e) {
return; // end this thread
}
}
public static void main(String[] args) {
Runnable ping = new RunPingPong("ping", 33);
Runnable pong = new RunPingPong("PONG", 100);
new Thread(ping).start();
new Thread(pong).start();
}
}
First, a new class that implements Runnable is defined. Its implementation of the run method is the same
as PingPong's. In main, two RunPingPong objects with different timings are created; a new THRead