Creating Threads in Java Using OOP Principles
1. By Extending the Thread Class
Concept:
- You create a subclass of the `Thread` class.
- Override the `run()` method to define the task.
- Create an instance and call `start()` to begin the thread.
Code Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running via Thread class.");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
Advantages:
- Simpler to use when not doing any other inheritance.
- No need to explicitly create a `Runnable` object.
Disadvantages:
- Java does not support multiple inheritance with classes, so you can't extend any other class if
you're already extending `Thread`.
2. By Implementing the Runnable Interface
Concept:
- Create a class that implements `Runnable`.
- Override the `run()` method with the thread logic.
- Pass the `Runnable` object to a `Thread` constructor.
Code Example:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running via Runnable interface.");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable task = new MyRunnable();
Thread t1 = new Thread(task);
t1.start();
}
}
Advantages:
- More flexible—allows your class to extend another class.
- Promotes separation of concerns—your task logic is in `Runnable`, and thread management is
in `Thread`.
- Reusability—the same `Runnable` can be used to create multiple threads.
Disadvantages:
- Slightly more complex to set up (involves two classes or objects).
Comparison Table
Feature Thread Class Runnable Interface
Inheritance Extends `Thread` Implements `Runnable`
Multiple Inheritance Not possible Possible
Task Reusability Not reusable Reusable
Separation of Concerns Task + Thread in same class Task logic separated
Better for Simple, short-lived threads Complex, reusable logic
Best Practice
In modern Java development:
- Prefer `Runnable` (or `Callable` for return values) over extending `Thread`, especially in
enterprise or modular code.
- It aligns better with object-oriented principles like abstraction and decoupling.