Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconRunnable Interface in Java: Implementation, Steps & Errors

Runnable Interface in Java: Implementation, Steps & Errors

Last updated:
1st May, 2021
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
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.

Check out our free courses to get an edge over the competition.

Explore our Popular Software Engineering Courses

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:

Check out upGrad’s Advanced Certification in DevOps

Ads of upGrad blog
  • 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.

Explore Our Software Development Free Courses

Check out upGrad’s Java Bootcamp

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.

In-Demand Software Development Skills

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

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

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.

Read our Popular Articles related to Software Development

Ads of upGrad blog

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

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.

Check out all the Trending Java Tutorial Topics in 2024.

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.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What is multithreading in Java?

Multithreading is a concept in Java in which tasks are executed simultaneously. It allows a program to perform many different tasks simultaneously instead of waiting for a single task to be completed. It is one of the most popular topics of Java and Java developers. Multithreading is one of the very powerful features of java. It uses CPU effectively by running several threads. Java has a special construct called a thread. A thread is basically a software process that can execute arbitrary sequence of Java bytecode instructions. The execution of each thread is independent from other threads. Developers can create a new thread any time and the JVM will handle the execution of this thread. This helps in developing highly scalable and responsive application.

2What is runnable interface in Java?

The runnable interface is used to write applications which can run in a separate thread. Any class that implements the runnable interface is called a thread. The code of the thread is executed by the interpreter after the thread is started. You can implement the runnable interface and create your own multithreading program. There are two ways to implement this interface. The first one is by using the thread subclass. The other one is by overriding the run() method.

3How does multithreading actually works?

Explore Free Courses

Suggested Blogs

8 Exciting Full Stack Coding Project Ideas & Topics For Beginners
3984
A Full stack developer is an engineer who can design and develop an end-to-end application independently by handling all the work of coding, databases
Read More

by upGrad

19 Feb 2024

17 Interesting HTML Project Ideas & Topics For Beginners [2024]
414761
Summary In this article, you will learn 10 Interesting HTML Project Topics. Take a glimpse below. A tribute page A survey form Technical documentati
Read More

by Rohan Vats

19 Feb 2024

How to Open json File in Excel
96575
What is JSON? JSON (JavaScript Object Notation) is a file format that is used for storing and exchanging data in the network. It is used to send data
Read More

by Rohan Vats

19 Feb 2024

JSP vs Servlet: Difference Between JSP & Servlet [2024]
52573
Websites are collections of static files, for example, images, graphics, and HTML files. These websites are referred to as web applications if they pr
Read More

by Rohan Vats

19 Feb 2024

Java Developer Salary in India in 2024 [For Freshers & Experienced]
900531
Wondering what is the range of Java developer salary in India? From choosing your first programming language to writing apps for Android and several
Read More

by Rohan Vats

19 Feb 2024

Polymorphism In OOPS: What is Polymorphism [Detailed Explanation]
124323
Polymorphism in OOPs is inseparable and an essential concept of every object-oriented programming language. An object or reference basically can take
Read More

by Rohan Vats

19 Feb 2024

Literals In Java: Types of Literals in Java [With Examples]
8124
Summary: In this article, you will learn about Literals in Java. Literals in Java Integral Literals Floating-Point Literals Char Literals String Lit
Read More

by Rohan Vats

19 Feb 2024

Top 30 Exception Handling Interview Questions and Answers [For Freshers & Experienced]
35816
Exception handling is a concept that is implemented in algorithms to handle possible runtime errors, which may disrupt the normal flow of a program. S
Read More

by Rohan Vats

19 Feb 2024

Top 40 MySQL Interview Questions & Answers For Beginners & Experienced [2024]
129732
Have a Data engineering or data science interview coming up? Need to practice some of the most asked MySQL interview questions? The article compiles t
Read More

by Rohan Vats

19 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon