Difference between “implements Runnable” and “extends Thread” in java

In java language, as we all know that there are two ways to create threads. One using Runnable interface and another by extending Thread class.

Thread

Here are some of my thoughts on whether I should use Thread or Runnable for implementing task in Java, though you have another choice as “Callable” for implementing thread which we will discuss later.

1) Java doesn’t support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.

2) In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread than use Runnable interface instead.

3) Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.

4) Separating task as Runnable means we can reuse the task and also has liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner.

5) Java designer recognizes this and that’s why Executors accept Runnable as Task and they have worker thread which executes those task.

6) Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.

7) Thread class approach, you must have to create separate instance for every thread access. Hence different memory is allocated for every class instances.

8) Coding to an interface rather than to implementation. This makes your software/application easier to extend. In other words, your code will work with all the interface’s subclasses, even ones that have not been created yet.

9)Interface inheritance (implements) is preferable – This makes your code is loosely coupling between classes/objects.

Note : Thread class internally implements the Runnable interface

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s