FROMDEV

Methods To Create Threads In Java – How They Differ From Each Other?

A comparison on thread class vs runnable interface approach in java for creating threads

Java is one of the most powerful languages. Its also a very popular and versatile language that is used by millions on application around the world.

Java Multi threading is considered most powerful tool of java. This is also one of the most frequently asked java interview topic. You may find many difficult java threading questions on this page.

Threading is one the things you must know as a java programmer. No java interview will complete without a discussion on threads.

Every good java book covers a big section of its chapters about threading.
Threads are considered one of the important aspects of Java and developers can create them by two popular ways – extending thread class and implementing runnable. In this post, we will check how both methods are different from each other and which option can be considered best out of two?

Two Ways To Create Thread In Java

You can create threads in java by extending Java.lang.thread class or by implementing java.lang.runnable interface.

Extend Threads Vs. Implement Runnable In Java

Multiple inheritance limitation

As you know, Java does not support multiple inheritances for extended classes. In case, if we extend any thread class then it cannot be used for any other purpose and it may cause overhead problem for additional methods.

At the same time, if you implement runnable interface then class can be extended for other purposes and overhead problem can be reduced significantly.

Best programming practice

In java, extending class simply means modifying or improving any existing class. If you don’t want to improve or modify it, then implanting runnable interface would be the best option to consider.

Reusability

Implementing runnable interface improves reusability of the code and makes it loosely coupled as it separates the task from runner. Extended class makes your code tightly coupled as single class acts as both container and runner.

Extended classes are specialized version of code; at the same time implementing runnable is generalized version of code. It is easy to maintain runnable interfaces without disturbing the runner.

Quick overview

Conclusion

After this discussion, it is clear that implementing runnable interface is certainly preferable choice over extending threads.

This article has been shared by Ethan Millar working with Aegis SoftTech as senior developer from last five years. He has extensive experience in Java web development, different java technologies and frameworks. The objective of writing this post is to discuss about right method to create threads. The conclusion has been drawn after practical research and implementation by Java development team at Aegis SoftTech.

Exit mobile version