The ‘Runnable’ interface in Java is a functional interface, which is used to represent a task that can be executed concurrently by a thread. Implementing the ‘Runnable’ interface allows you to define the source code that should be executed in a separate thread. This article explores the steps to implement the ‘Runnable’ interface and discusses common errors that developers might encounter while implementing the Runnable Interface in Java.
What is a Runnable Interface in Java?
The ‘Runnable’ interface is a functional interface, meaning it has a single abstract method, “run().” This method defines the code that constitutes the task to be executed by a thread. The interface is simple yet powerful, providing a way to encapsulate a unit of work that can be worked on by multiple threads concurrently.
Syntax of the Runnable interface
@FunctionalInterface
public interface Runnable {
public abstract void run();
}

POSTGRADUATE PROGRAM IN
Multi Cloud Architecture & DevOps
Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems.
run() Method of the Runnable Interface
The ‘run()’ method is the single abstract method defined by the ‘Runnable’ interface. It is where you place the source code that should be executed when a thread is started. The method is central to the Java threading model, providing a simple and standardized way to define tasks that can be run concurrently.
Steps to Create a New Thread Using Runnable Interface in Java
We can create a new thread using the Runnable interface by the following steps in Java.
- Create a class that implements the Runnable interface.
- Override the run() method of the Runnable interface in the class
- Create a Thread class object in the main class by passing the class object that implemented the Runnable interface.
- Call the start() method of the Thread object.
Implementation of Runnable Interface in Java language
Let’s implement the Runnable Interface in Java language. In this program, we will implement the Runnable interface to the MyRunnable class and override the run() method. The code inside run() is what the thread will execute.
The following program demonstrates the Runnable Interface
Program
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable(); // Step 2: Create a Runnable object
Thread thread = new Thread(myRunnable); // Step 3: Create a Thread object
thread.start(); // Step 4: Start the Thread
}
}
Output
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Exceptions Encountered When Implementing the Runnable Interface in Java
The overridden run() method is not allowed to throw checked exceptions, such as Exception, which are checked at compile time. It can only throw unchecked exceptions that occur at runtime, like RuntimeException. Specifically, the run() method can only throw RuntimeException or any exceptions that are subclasses of RuntimeException.
Checked Exception Inside run() Method
public class PrintMessage implements Runnable {
private final String message; // The message to be printed
// Constructor for the PrintMessage class
public PrintMessage(final String message) {
this.message = message;
}
// The run method is called when the thread is started
@Override
public void run() throws Exception {
if (message == null) {
// If the message is null, throw an exception
throw new Exception("Message cannot not be null");
}
// Otherwise, print the message to the console
System.out.println(message);
}
}
After compiling the code class throws the below error because exception is a checked exception.
.\PrintMessage.java:10: error: run() in PrintMessage cannot implement run() in Runnable
public void run() throws Exception {
^
overridden method does not throw Exception
1 error
error: compilation failed

82.9%
of professionals don't believe their degree can help them get ahead at work.
Unchecked Exception Inside run() Method
The following source code does not throw any run-time error because the run() method can throw unchecked exceptions. The following program demonstrates the Unchecked Exception
public class PrintMessage implements Runnable {
private final String message; // The message to be printed
// Constructor for the PrintMessage class
public PrintMessage(final String message) {
this.message = message;
}
// The run method is called when the thread is started
@Override
public void run() throws RuntimeException {
if (message == null) {
// If the message is null, throw a RuntimeException
throw new RuntimeException("Message cannot not be null");
}
// Otherwise, print the message to the console
System.out.println(message);
}
}
Use Cases of the Runnable Interface in Java
The Runnable interface in Java is a key part of the threading framework. It allows for concurrent execution of source code. Let’s see some use cases of the Runnable Interface in Java language.
- Multithreading in Application: A runnable interface enhances performance by running multiple threads concurrently, such as in games or simulations.
- Background Tasks: Offloads tasks like file downloading or database operations to run in the background.
- Asynchronous Processing: This handles operations like I/O without blocking the main thread.
- Handing User Interface Events: Runnable Interface prevents UI freezing by handling long-running tasks in separate threads.
- Parallel Data Processing: Speeds up computations by processing large datasets in parallel.
- Thread Pool Management: Manages a pool of threads for executing tasks in enterprise applications.
Thread Class Vs Runnable Interface
| Criteria | Thread Class | Runnable Interface |
| Inheritance | Requires extending the ‘Thread class | Implements the Runnable interface |
| Multiple Inheritance | Not possible to extend another class | Allows extending another class. |
| Resource Sharing | Each thread has its own instance, making sharing resources difficult | The multiple threads can share the same instance. |
| Decoupling of Task and Thread | Task and thread are tightly coupled | Task and thread are decoupled, offering more flexibility. |
| Reusability | Less reusable since the task is tied to the thread | The more reusable as the task can be passed to multiple threads. |
| Memory Overhead | Higher due to additional thread object overhead | Lower, as only one instance of ‘Runnable’ is required. |
Conclusion
The ‘Runnable’ interface in Java is a powerful tool for implementing multithreading. Separating the task from the thread provides greater flexibility, allowing your class to extend other classes and enabling resource sharing among multiple threads.
When a developer implements a Runnable interface, they must be aware of potential errors like missing the ‘run’ method or incorrectly managing shared resources. However, when done correctly, using the ‘Runnable’ interface leads to cleaner, more modular source code, which is especially beneficial in complex, large-scale applications.
1. What is the ‘Runnable’ interface in Java?
2. Can I pass parameters to the ‘run()’ method?
3. What should I need to handle exceptions within the ‘run()’ method?
4. Can ‘Runnable’ return a result?
5. Can ‘Runnable’ be used with ‘ExcutorService’?
Updated on August 14, 2024
