As discussed in Java multi-threading article we can define a thread in the following two ways:
- By extending Thread class
- By implementing Runnable interface
In the first approach, Our class always extends Thread class. There is no chance of extending any other class. Hence we are missing Inheritance benefits. In the second approach, while implementing Runnable interface we can extends any other class. Hence we are able to use the benefits of Inheritance.
Because of the above reasons, implementing Runnable interface approach is recommended than extending Thread class.
The significant differences between extending Thread class and implementing Runnable interface:
- When we extend Thread class, we can’t extend any other class even we require and When we implement Runnable, we can save a space for our class to extend any other class in future or now.
- When we extend Thread class, each of our thread creates unique object and associate with it. When we implements Runnable, it shares the same object to multiple threads.
Lets have a look on the below programs for better understanding:
Main method executed by main thread Run method executed by child Thread
Hello Visitors Main method executed by main thread Run method executed by child Thread
NOTE : In the case of multithreading we cant predict the exact order of output because it will vary from system to system or JVM to JVM.
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Runnable interface in Java
- Naming a thread and fetching name of current thread in Java
- Difference between Thread.start() and Thread.run() in Java
- How a thread can interrupt an another thread in Java?
- Java.lang.Thread class in Java
- Thread Pools in Java
- Daemon thread in Java
- Main thread in Java
- Main App Implements Runnable | Concurrent Programming Approach 2
- Lifecycle and States of a Thread in Java
- Thread Safety and how to achieve it in Java
- Java Thread Priority in Multithreading
- Inter-thread Communication in Java
- Thread UncaughtExceptionHandler in Java with Examples
- Lock framework vs Thread synchronization in Java
- Thread Interference and Memory Consistency Errors in Java
- isAlive() and join() methods of Thread Class in Java
- How to implement SQL GROUP BY in Java?
- How to implement an Interface using an Enum in Java
- How to implement our own Dynamic Array class in Java?