A thread can be implemented as per the below given options
- A Java class extending the Thread class
- A Java class implementing the runnable interface
Thread vs Runnable – Which one is better for implementation : Java newbies have long struggled with choosing between threads and runnable. Comparing Thread to Runnable, Java threads seems simpler because you only need to deal with the java.lang class. When Runnable is used to implement Thread, you must deal with both the Thread and Runnable classes. Although choosing between Runnable and Thread should take into account the differences between the two frameworks as well as the advantages and disadvantages of each strategy
The difference between thread and runnable is the most commonly asked interview question, and the majority of the interviewers are quite curious to know your reasoning for selecting Thread over Runnable or the contrary. We will attempt to highlight some key differences between Java’s Runnable and Thread constructs so that you may make an informed choice.
Difference between Java Thread and Runnable interface in java
The below given are the main differences between the Java thread and runnable interface which you must know
Thread Class in java | Runnable interface in java |
Thread is a class in java provided to create threads at runtime | Runnable is a functional interface which is used to create a thread at runtime |
Thread class provides many methods like start() , stop() and run() | Runnable interface provides only abstract method run() |
Each thread when executed creates a unique instance per task execution | When using runnable interface, multiple threads share the same objects |
Thread execution requires more memory | When using runnable interface, memory consumption is less |
If a class extends Thread class, then it cannot extend another class as java does not support multiple inheritance | When using runnable interface , a class can extend another class |
When should we use Runnable Interface in Java ?
When you want a collection of threads to access the same resource, use the Runnable interface. Avoid using the Thread class in this situation since creating numerous objects uses much more memory and has a significant performance impact.
In addition, there are some suggestions for improved coding in object-oriented architectures.
- Instead of implementing, you’re coding to an interface. Your software/application can be expanded more easily as a result. In other words, even uncreated subclasses of the interface will be compatible with your code.
- It is recommended to use interface inheritance (implements) because it allows your code to be loosely coupled between classes and objects.(Note: The Runnable interface is internally implemented by the Thread class.)