Which is better extending thread class or implementing runnable interface
Thread is a block of code which can execute concurrently with other threads in the JVM. You can create and run a thread in either ways; Extending Thread class, Implementing Runnable interface.
The basic difference is that:
- When you extends Thread class, after that you can't extend any other class which you required. (As you know, Java does not allow inheriting more than one class).
- When you implements Runnable, you can save a space for your class to extend any other class in future or now.
But the major difference and important one is:
- When you extends Thread class, each of your thread creates unique object and associate with it.
- When you implements Runnable, we can use threadpool to share the same object to multiple threads.
In the Runnable interface approach, only one instance of a class is being created and it has been shared by different threads. So the value of counter is incremented for each and every thread access.
Whereas, Thread class approach, you must have to create separate instance for every thread access. Hence different memory is allocated for every class instances and each has separate counter, the value remains same, which means no increment will happen because none of the object reference is same.
When to use Runnable?
Use Runnable interface when you want to access the same resource from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead.
Use Runnable interface when you want to access the same resource from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead.
Apart from this, object oriented designs have some guidelines for better coding.
- 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.
- Interface inheritance (implements) is preferable – This makes your code is loosely coupling between classes/objects.(Note : Thread class internally implements the Runnable interface)
You must extend Thread only when you are looking to modify run() and other methods as well.
Such as ThreadGroup group, thread name, long stackSize, priority.
If you are simply looking to modify only the run() method implementing Runnable is the best option (Runnable interface has only one abstract method i.e. run() ).
Read full article from Which is better extending thread class or implementing runnable interface