Thread Class vs Runnable Interface with Examples
#Thread Class vs Runnable Interface with Examples
Introduction
Multithreading is a powerful feature in Java that allows concurrent execution of two or more parts of a program. To achieve multithreading, developers need to create threads. In Java, there are two main ways to create threads:
By extending the Thread class
By implementing the Runnable interface
Both approaches have their use cases and trade-offs. Let’s explore them with examples.
The simplest way to create a thread is by extending the Thread
class and overriding its run()
method.
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running using Thread class...");
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Starts the thread
}
}
Key Points:
Easy to implement.
Not flexible because Java does not support multiple inheritance. If you extend Thread
, you cannot extend another class.
A more flexible way is to implement the Runnable
interface and pass it to a Thread
object.
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running using Runnable interface...");
}
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
Key Points:
Provides better reusability.
Allows extending another class while still supporting multithreading.
Preferred in real-world applications.
Feature | Thread Class | Runnable Interface |
---|---|---|
Inheritance Limitation | Cannot extend another class | Can extend another class |
Code Reusability | Less reusable | More reusable |
Implementation | Simple but less flexible | Flexible and widely used |
Real-world Usage | Rarely used | Preferred approach |
class MultiThreadDemo implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
public static void main(String[] args) {
Thread t1 = new Thread(new MultiThreadDemo(), "Thread-1");
Thread t2 = new Thread(new MultiThreadDemo(), "Thread-2");
t1.start();
t2.start();
}
}
Output:
Thread-1 is running
Thread-2 is running
Use Runnable interface when possible (more flexible and reusable).
Use Thread class for simple, one-off implementations.
Always call start()
instead of run()
directly.
Creating threads in Java can be done either by extending Thread class or implementing Runnable interface. While both are valid, the Runnable approach is recommended for scalable and maintainable applications.
SEO Keywords to Target:
Creating threads in Java
Thread class vs Runnable interface
Java multithreading examples
Runnable vs Thread in Java
How to create threads in Java