Making a Thread
The choice between extending the Thread class or
implementing the Runnable interface with your
application objects is sometimes not an obvious one. It’s also
usually not very important. Essentially, the difference between the
two classes is that a Thread is supposed to
represent how a thread of control runs (its
priority level, the name for the thread), and a
Runnable defines what a
thread runs. In both cases, defining a subclass usually involves
implementing the run() method to do whatever
work you want done in the separate thread of control.
Most of the time we want to specify what runs in a thread, so in most
cases you may want to implement the Runnable
interface. With a Runnable subclass, you can use
the same object with different types of Thread
subclasses, depending on the application. You might use your
implementation of Runnable inside a standard
Thread in one case, and in another you might run
it in a subclass of Thread that sends a notice
across the network when it’s started.
On the other hand, directly extending Thread can
make your classes slightly easier to use. You just create one of your
Thread subclasses and run it, instead of
creating a Runnable subclass, putting into
another Thread, and running it. Also, if your
application objects are subclasses of Thread, then you can access them directly by asking the system for the current thread, or the threads in the current thread group, etc. Then you can cast the object to its subclass and call specialized ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access