Threading Using the Runnable Interface

As simple as it is to create another thread of control, there is one problem with the technique we’ve outlined so far. It’s caused by the fact that Java classes can inherit their behavior only from a single class, which means that inheritance itself can be considered a scarce resource, and is therefore “expensive” to the developer.

In our example, we are threading a simple loop, so this is not much of a concern. However, if we have a complete class structure that already has a detailed inheritance tree and want it to run in its own thread, we cannot simply make this class structure inherit from the Thread class as we did before. One solution would be to create a new class that inherits from Thread and contains references to the instances of the classes we need. This level of indirection is an annoyance.

The Java language deals with this lack of multiple inheritance by using the mechanism known as interfaces.[2] This mechanism is supported by the Thread class and simply means that instead of inheriting from the Thread class, we can implement the Runnable interface (java.lang.Runnable), which is defined as follows:

public interface Runnable {
     public abstract void run();
}

The Runnable interface contains only one method: the run() method. The Thread class actually implements the Runnable interface; hence, when you inherit from the Thread class, your subclass also implements the Runnable interface. However, in this case we want to implement the Runnable ...

Get Java Threads, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.