Creating Threads in Java: Extending Thread vs. Implementing Runnable π
In Java, you can create threads using two main approaches:
- Extending the
Thread
class` - Implementing the
Runnable
interface
Both approaches have their advantages and are used based on specific requirements.
1. Extending the Thread Class ποΈ
- A subclass inherits from
Thread
and overrides therun()
method. - Less flexible since Java allows single inheritance.
Example Code
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String args[]) {
MyThread t1 = new MyThread();
t1.start();
}
}
Real-Life Example ππ§
Imagine an assembly line where each machine (thread) performs a specific task like welding or painting.
2. Implementing the Runnable Interface π
- More flexible as the class can extend other classes while implementing
Runnable
. - Recommended for better scalability.
Example Code
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread is running...");
}
public static void main(String args[]) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
Real-Life Example π’
A company where multiple employees (threads) work independently but share resources like databases.
Choosing the Right Approach π€
Feature | Extending Thread | Implementing Runnable |
Multiple Inheritance Support | β No | β Yes |
Code Reusability | β Less | β More |
Memory Overhead | β Low | β Low |
Conclusion π―
- Use
Thread
when no other class needs to be extended. - Use
Runnable
for better flexibility and reusability.
By selecting the right approach, developers can optimize performance and maintainability in Java applications!
0
Subscribe to my newsletter
Read articles from ππ¬π³π¦π°π₯ ππ¬πΆππ© directly inside your inbox. Subscribe to the newsletter, and don't miss out.
ThreadsProgramming BlogsProgramming Tipsprogramming languagescodingOpen SourceObject Oriented ProgrammingComputer Science#codenewbiesJavaDSADeveloperData ScienceWeb Developmentwebdev
Written by
