If anybody asks - What are the two methods of using Threads in Java? The answer is on our tip of tongue- TWO, but further if it is asked what is the difference between threads implemented via extending Thread class and implementing runnable interface? we feel dificulty in explaining. Here some of my thoughts are presented to draw a line among them.
- As we all know Java doesn't support multiple inheritance. If you want to extend the Thread class then it will make your class unable to extend other classes as java is having single inheritance feature whereas If you implement runnable interface, you can gain better object-oriented design and consistency and also avoid the single inheritance problems.
- In OOP, we extend a class for adding some new behaviour. If we are not making any modification on Thread than its a good OOP design to use Runnable interface.
- When we extend a thread class, all the Properties and Behaviours of Thread class and inherited by the subclass, its kind of overhead if we are not going to use it and the same can be achieved on ease with Runnable.
- Runnable interface represent Task and the same gives flexibility to get them executed by either Executors or Thread or any other means. So it draws a line between Task as Runnable than Thread as good design decision. However Executors accept Runnable as Task and they have worker thread which executes those tasks, but that's a totally different point.
- While we are differentiating task as Runnable exhibits it can be reused and we are also provided with liberty to execute it from different means. As we know, a thread cannot be restarted once it's complete so again Runnable seems more promising.
A Short Note on Callable and Runnable:
Both the interfaces are implemented by those classes who want to execute a thread of execution, but few notable differences are as follows:
- A Thread implemented via Callable interface may return a value, whereas its not possible if we are using a Runnable interface.
- A Thread implemented via Callable interface may throw checked exceptions, whereas its not possible if we are using a Runnable interface.
What I feel, the developers of Java felt a need of enhancing the capabilities of the Runnable interface, without changing the usage of the Runnable interface and that is why probably they've developed Callable interface.
I hope this will clear some of the doubt clouds about threads.