Java Reference
In-Depth Information
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 de-
clares 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 computa-
tion 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
Run-
nable
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 ver-
sions, 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) {