Extends Thread vs Implements Runnable

Extends Thread vs Implements Runnable

It is a big question, even in interviews, which style of creation of thread is preferable. Explained in simple terms. Start reading.

Thread creation styles

There are two ways of creating threads – one by extending Thread class and the other by implementing Runnable interface. Now the discussion is which to prefer in normal situations.

I put both for an eye glance here before reasoning starts.

Extends Thread vs Implements Runnable
  1. We extend some class either to use the class as it is or modify the behaviour of its methods by overriding. We are not changing the behaviour of Thread class. Just we are interested to use start() and sleep() methods etc. as it is (with the original behaviour intended by the Designers). So better use Thread class by composition by implementing Runnable interface.
  2. Advantage of implementing Runnable is, at the same time, we can extend another class as follows (remember, Java does not support multiple inheritance).
  3. public class Animation extends Applet implements Runnable

    In the above code, Animation class can make use Applet class methods to run in a browser. Also can make use of Thread class methods by composition (like t1.start()).

  4. Interface always gives a cleaner separation between your code and Thread class methods implementation.
  5. When Thread is extended, d1 object becomes implicitly a thread and starting it as a thread itself with d1.start(). When Demo is implemented with Runnable, d1 is not a thread at all. You are taking the help of a Thread object t1 to execute Demo class run() method. This is better approach as you can pass d1 object to any other service that can call run() method. Thus the code becomes more flexible in larger applications.
  6. When Thread is extended, each thread created should be started separately. But with Runnable, the same t1 service can be used to start many threads one by one.

2 thoughts on “Extends Thread vs Implements Runnable

  1. Adi

    Hi sir,

    I have got a doubt. You said when Demo implements Runnable interface then d1 object is not thread at all i did not get this point. Could you please tell me why d1 object is not thread at all.


    1. S. Nageswara Rao, Corporate Trainer Post author

      By definition, if you extend Thread class, then the object created becomes implicitly thread. Otherway to say perfectly, the object of the class can make use of the Thread class methods to create thread. When you implement Runnable, the class cannot make use of the Thread class methods (like start()) and thereby I call myself, the object is not thread.

Leave a Reply

Your email address will not be published. Required fields are marked *