What is difference between Runnable and Thread? What is the best way to create thread?

There are 2 ways of creating thread. First way is by extending Thread class and another is implementing Runnable interface. What are the differences between these 2 ways. This is frequently asked question in Java interviews.

1. Multiple Inheritance: Thread is a class. Once you extend Thread class, you can not extend other class because Java does not support multiple inheritance. Whereas Runnable is interface so you can extend other class while implementing Runnable interface.

2. Worker and Job: Thread is worker which works on job(Runnable). It is always a good practice to separate code of worker and job. If we create thread by extending Thread class, It will combine code of worker and job.
So it is good practice to implement Runnable interface. Object of this class(Job) will be passed to thread constructor(Worker). The thread instance will call run method on class which implements Runnable. This is how we can separate Worker and its Job.

3. extends means adding new Feature: When Subclass extends Superclass, it means Subclass is adding additional functionality to Superclass. But we do not provide any addition functionality to Thread class by extending it. We just want to create thread and override run method. So it is good design to implement Runnable interface.

Runnable interface won in above discussion. We should always create thread by implementing Runnable interface.  

Comments

Popular posts from this blog

Data types and Literals in Java

How to define Auxiliary Constructor in case class in Scala

equals() method of Object class in Java