Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Runnable Interface in Java – Steps to Implement & Errors

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

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(); }

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
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

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.

FAQs
The ‘Runnable’ interface is a functional interface in Java that represents a task that can be executed by a thread. It contains a single abstract method. ‘run()’, which needs to be overridden to define the code that will be executed by the thread.
The  ‘run()’ method cannot accept parameters directly. If you need to pass parameters, you should set them up within the class that implements ‘Runnable’ or use other methods to initialize them.
We can handle exceptions within the ‘run()’ method using the try-catch blocks. Since the ‘run()’ method does not declare any checked exceptions, you need to handle them appropriately within the method itself.
No, ‘Runnable’ cannot return a result. Use ‘callback’ for tasks that need to return a result.
Yes, Runnable tasks can be submitted to an ‘ExecutorService’ for concurrent execution of management.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved