Runnable Interface in Java: Implementation, Steps & Errors

Introduction

A runnable interface in Java is an interface whose instances can run as a Thread. While working with Threads, the runnable interface acts as a core element of the Java programming language. Java classes created to run Threads must implement this interface. This article will give you a deep understanding of the runnable interface in Java and the implementation process.

What is the Runnable Interface in Java?

A runnable interface is an interface that contains a single method. The Java program defines this single method in java.lang package and calls it upon the execution of the thread class. It provides a template for objects that a class can implement using Threads. You can implement the runnable interface in Java in one of the following ways:

  • Using subclass thread
  • Overriding the run() method

Java does not allow multiple inheritances in the program. You can extend only one class, and when you extend a thread class, it consumes more memory, computation time, and other resources. Hence, it adds the overhead of using additional methods. Out of the above two options, it is better to use a runnable interface to create a thread. To do so, you must provide the implementation for the run() method.

Steps for Creating a Thread Using Runnable Interface in Java

Perform the following steps for creating a thread using the runnable interface in Java.

  1. Create a thread class that will implement the runnable interface.
  2. In the thread class, write a function to override the run() method.
  3. Create an instance of the Thread class.
  4. The thread instance has a constructor which accepts the runnable object. Pass this object as a parameter to the thread instance.
  5. Finally, call the start method of the thread instance.

Also Read: Java Project Ideas & Topics

Implementation of the Runnable Interface in Java

Implementation of the run() method is the easiest way of creating a new thread. It acts as a starting point for creating a new Thread. The runnable interface implementation uses the code inside the run() method and executes it on a concurrent thread. You can either invoke class, create new variables, or call the action in the run() method to implement the runnable interface in Java. The program ensures that the thread is inactive until it prints the return statement in the code.

public class TestRunnableInterface {

public static void main(String[] args) {

    System.out.println(“From primary() method: ” + Thread.currentThread().getName());

    System.out.println(“Implementing the runnable interface in Java“);

    Runnable instance = new Runnable() {@Override

        public void run() {

             System.out.println(“From run() method: ” + Thread.currentThread().getName());

   }

};

    System.out.println(“Create a new instance of the thread object.”);

Thread test = new Thread(instance);

    System.out.println(“Executing the thread!”);

test.start();

  }

}

Output

From primary() method: main

Implementing the runnable interface in Java

Create a new instance of the thread object.

From run() method: Thread-0

Errors Encountered When Implementing the Runnable Interface in Java

The run() method throws a runtime exception error when the program breaks due to syntax or code error. If a Java virtual machine does not detect the errors, then the created thread handles the exception missed by the JVM. The exception handler prints the exception and stops the program.

import java.io.FileNotFoundException;

public class TestRunnableInterface {

  public static void main(String[] args) {

    System.out.println(“The primary thread is: ” + Thread.currentThread().getName());

Thread test = new Thread(new TestRunnableInterface().new DemoInstance());

test.start();

  }

  private class DemoInstance implements Runnable {

public void run() {

      System.out.println(Thread.currentThread().getName() + “, invoking the run() method!”);

   try {

     throw new FileNotFoundException();

   }

      catch(FileNotFoundException demo) {

        System.out.println(“Caught an Error!”);

     demo.printStackTrace();

   }

}

  }

}

Output

The primary thread is: main

Thread-0, invoking the run() method!

Caught an error!

java.io.FileNotFoundException

at TestRunnableInterface$DemoInstance.run(Example.java:21)

at java.lang.Thread.run(Thread.java:748)

The TestRunnableInterface class in the above program does not throw the FileNotFoundException exception. The Java virtual machine takes care of the exceptions which should have been handled by the TestRunnableInstance class.

Use Case of the Runnable Interface in Java

The runnable interface in Java is used in a networking scenario where the server receives multiple connection requests from clients. The runnable interface in Java handles it quickly and efficiently by performing multi-thread programming.

Conclusion

In a nutshell, a runnable interface in Java is always a better choice compared to the subclass thread when it comes to creating threads in Java. The code used in the article is only for explanatory purposes. You can modify the statements given in the examples as per your requirements. In this article, we learned about the runnable interface in Java and how you can create a thread by implementing the runnable interface in Java.

You can try out the code to strengthen your Java constructor’s knowledge. If you want to gain an in-depth understanding of Java, check out the upGrad Executive PG Programme in Full Stack Development course. This course is designed for working professionals and offers rigorous training and job assistance with top companies.

Prepare for a Career of the Future

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN FULL STACK SOFTWARE DEVELOPMENT
LEARN MORE

0 replies on “Runnable Interface in Java: Implementation, Steps & Errors”

×