Introduction
Multithreading is one of the most powerful features of Java, allowing multiple tasks to run concurrently within a single application. This capability improves application performance, responsiveness, and resource utilization. Whether you’re developing desktop software, web applications, Android apps, or enterprise systems, understanding multithreading is essential.
Java provides two primary ways to create threads:
- Extending the Thread class
- Implementing the Runnable interface
Among these, implementing the Runnable interface is considered the preferred and more flexible approach because it supports better object-oriented design and allows your class to extend another class if needed.
The Runnable interface is part of the java.lang package and contains only one abstract method, run(). The code inside this method defines the task that should be executed by a thread.
What is the Java Runnable Interface?
The Runnable interface is a functional interface in Java that represents a task that can be executed by a thread.
Instead of extending the Thread class, a class implements the Runnable interface and provides the implementation of the run() method. A Thread object is then created by passing the Runnable object to the Thread constructor.
This approach separates the task from the thread, making your code more reusable, flexible, and maintainable.
Key Features
- Part of the java.lang package
- Functional interface (contains one abstract method)
- Defines the run() method
- Preferred way to create threads
- Supports multiple inheritance through interfaces
- Promotes better object-oriented programming
Syntax
The basic syntax for implementing the Runnable interface is shown below.
@Override
public void run() {
// Code executed by thread
}
}
public class Main {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
}
}
How Runnable Interface Works
The process of creating a thread using Runnable consists of four simple steps.
- Create a class that implements Runnable.
- Override the run() method.
- Create a Runnable object.
- Pass the object to the Thread constructor and call start().
Create Runnable Class
↓
Override run()
↓
Create Runnable Object
↓
Pass to Thread Constructor
↓
Call start()
↓
run() Executes
Example 1: Basic Runnable Interface Example
class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Thread is running...");
}
}
public class Main {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
}
}
Output
Example 2: Multiple Threads Using Runnable
class MyTask implements Runnable {
@Override
public void run() {
for(int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread t1 = new Thread(task, "Thread-A");
Thread t2 = new Thread(task, "Thread-B");
t1.start();
t2.start();
}
}
Sample Output
Thread-B : 1
Thread-A : 2
Thread-B : 2
…
The exact output may vary because thread scheduling is controlled by the JVM.
Why Runnable is Preferred Over Thread Class
Although both approaches create threads, the Runnable interface provides several advantages.
1. Supports Inheritance
Java does not support multiple inheritance of classes.
Using Thread:
class MyThread extends Thread {
}
Using Runnable:
class Employee extends Person implements Runnable {
}
The class can extend another class while still supporting multithreading.
2. Better Code Reusability
The same Runnable object can be used by multiple Thread objects.
Runnable task = new MyTask();
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
3. Better Object-Oriented Design
Runnable separates:
- Task (Runnable)
- Thread (Thread object)
This makes applications easier to maintain.
Runnable Interface vs Thread Class
| Runnable Interface | Thread Class |
|---|---|
| Interface | Class |
| Implements Runnable | Extends Thread |
| Better flexibility | Less flexible |
| Supports inheritance | No multiple inheritance |
| Preferred approach | Mainly used for learning |
| Task and thread are separate | Task and thread are combined |
Runnable as a Functional Interface
Since Java 8, Runnable is a functional interface, which means it can be implemented using a lambda expression.
Traditional approach:
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("Running...");
}
};
Using Lambda Expression:
Runnable task = () -> {
System.out.println("Running...");
};
Thread thread = new Thread(task);
thread.start();
This makes the code shorter and more readable.
Example 3: Runnable with Lambda Expression
public class Main {
public static void main(String[] args) {
Runnable task = () -> {
for(int i = 1; i <= 3; i++) {
System.out.println("Message " + i);
}
};
Thread thread = new Thread(task);
thread.start();
}
}
Output
Message 2
Message 3
Common Methods Used with Runnable
Although the Runnable interface only defines the run() method, it is commonly used with methods from the Thread class.
| Method | Description |
|---|---|
| start() | Starts a new thread |
| run() | Contains the task to execute |
| sleep() | Pauses thread execution |
| join() | Waits for another thread |
| currentThread() | Returns the current thread |
| getName() | Gets thread name |
| setName() | Changes thread name |
| isAlive() | Checks if thread is running |
Real-Life Example
Consider a food delivery application.
When a customer places an order, several tasks happen simultaneously:
- Process payment
- Assign delivery partner
- Update restaurant
- Send SMS notification
- Update order tracking
Each of these tasks can run independently.
Customer Order
|
----------------------------------------
| | | | |
Payment Delivery Restaurant SMS Tracking
Instead of waiting for one task to complete before starting another, Java executes each task in a separate thread using Runnable.
Advantages of Runnable Interface
- Preferred way to create threads
- Supports better object-oriented programming
- Allows extending another class
- Better code reuse
- Separates task from thread
- Compatible with thread pools
- Works well with lambda expressions
- Easier to maintain and test
Disadvantages
- Requires creating a separate Thread object
- Slightly more code than extending Thread
- Beginners may find the two-object approach confusing
Despite these minor drawbacks, Runnable is the recommended approach in professional Java development.
Best Practices
- Always implement Runnable instead of extending Thread when possible.
- Call start() instead of run().
- Keep the run() method focused on a single task.
- Handle exceptions properly.
- Avoid creating too many threads.
- Use ExecutorService for managing large numbers of concurrent tasks.
- Synchronize shared resources when multiple threads access them.
Common Mistakes
1. Calling run() Directly
Incorrect:
Thread thread = new Thread(new MyTask());
thread.run();
Correct:
Thread thread = new Thread(new MyTask());
thread.start();
Calling run() directly executes the code in the current thread instead of creating a new one.
2. Forgetting to Override run()
Incorrect:
class MyTask implements Runnable {
}
This causes a compilation error because the run() method must be implemented.
Correct:
class MyTask implements Runnable {
@Override
public void run() {
}
}
3. Sharing Unsynchronized Data
When multiple threads access shared variables without synchronization, inconsistent results may occur.
Always synchronize shared resources or use concurrent collections when necessary.
4. Creating Too Many Threads
Creating hundreds or thousands of threads can reduce application performance.
Instead, use thread pools with ExecutorService.
5. Ignoring InterruptedException
Methods like Thread.sleep() can throw InterruptedException.
Always handle or propagate the exception appropriately.
Conclusion
The Java Runnable interface is the recommended way to create threads because it promotes flexibility, reusability, and clean object-oriented design. By separating the task from the thread, Runnable allows developers to write more maintainable and scalable applications while still taking advantage of Java’s powerful multithreading capabilities.
Unlike extending the Thread class, implementing Runnable lets your class inherit from another class, making it suitable for real-world software development. It is also compatible with modern Java features such as lambda expressions and the ExecutorService framework, which simplify concurrent programming and improve performance.