Runnable vs Thread in Java
In Java, you have two main ways to create a thread: by extending the Thread class or by implementing the Runn able interface. Each method has its own use cases and advantages. Understanding when to use one over the other can help in designing efficient and maintainable multithreaded applications.

Table of Contents
Thread Class
- When to Use:
- When you need to override or enhance the functionality of the Thread class.
- When you do not need to inherit from any other class.
Advantages
- Â Simpler and more straightforward for quick and simple threading needs.
- Â Direct access to the Thread class’s methods and functionalities.
Disadvantages
 Java does not support multiple inheritance, so if you extend the Thread class, you cannot extend any other class.
Runnable vs Thread
- When to Use:
- When your class needs to extend another class (since Java supports single inheritance only).
- When you want to separate the task to be performed from the mechanics of threading.
- Advantages:
- Â Promotes better object-oriented design by separating the task from the threading mechanism.
- Â More flexible as it allows the class to extend other classes.
- Disadvantages:
- Slightly more verbose since you need to pass the instance to the Thread object.
Using Thread Class
java
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread ID: " + Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
Using Runnable Interface
java
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread ID: " + Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}