Starting a Thread Using the Thread Class or the Runnable Interface

You can start a thread in Java by either implementing the java.lang.Runnable interface or by extending the java.lang.Thread class (see Tip “Weaving Threads”). How do you decide which mechanism to use?

Remember that if you extend the Thread class into a user-defined class, you are using up the single inheritance facility given to you by Java. That is, if you extend from Thread, you cannot simultaneously extend from another class. The only way you can add behavior from another previously defined class is by implementing the interface for that class in your user-defined class. This code illustrates this predicament:

 1. public MyClass implements MyInterface{2. }3. public MyThread extends Thread implements MyInterface {4.   MyClass myObject;5. 6.   // Provide delegation methods for myObject here7. }

As you can see, the class MyThread has to delegate to a local object myObject in order to reuse the behavior for MyInterface. If MyInterface had 30 methods, you would have to provide wrapper methods for 30 methods in MyThread.

On the other hand, implementing the Runnable interface only requires an implementation for the run() method. Since Runnable is an interface, you can still extend from another class:

 1. public MyThread extends MyClass implements Runnable {2. }

In general, implementing the Runnable interface presents a more flexible choice. Another thing to keep in mind is that the Thread class provides implementation for several other methods (besides run()) that you may never use. This overhead can also be avoided by using the Runnable interface.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: