What is the Runnable Interface in Java?

The java contains a type of functional interface called Runnable (stored in class java.lang.Runnable). It works to provide a standard protocol to the active objects intended to execute code. In other words, Runnable is the primary template for objects to enable thread execution.

Additionally, the Runnable interface allows a class to be active without having to subclass Thread. When a class implements the Runnable interface does not need subclassing Thread for execution. The developer must instantiate a Thread instance and pass it as the target.

The Runnable interface became helpful when a program requires to run() to get executed. The developer can implement this interface by defining a no-argument single method called run(). The run() method contains the code a thread wants to execute.

Thus, when a class implements a runnable interface must have to override the run() method. As this method uses void data type, it returns nothing.

Syntax:

Below is the method declaration syntax:

public void run()

Implementing Runnable

Implementing Runnable makes creating a thread simple. Implementing Runnable creates a thread for any object. An implementation of a Runnable requires only the implementation of the run method.public void run()

Using this method, we can execute code concurrently. As in the main thread, this method uses variables, instantiates classes, and performs actions. This thread remains until the method returns. As soon as the run method gets invoked, it creates a new thread.

Java Runnable Interface Step-By-Step

Implementing the Runnable interface in Java involves the following steps:

  • The process begins with creating a class implementing the Runnable interface.
  • Next, you should override the run method in Runnable.
  • Once you have created the Thread class, call the constructer with the Runnable object as a parameter. We can now execute our Runnable class using this Thread object.
  • The final step is to call the start method on the Thread object.

Code Sample

public class SampleClass implements Runnable {

    @Override
    public void run() {
        System.out.println("Thread ended");
    }

    public static void main(String[] args) {
        SampleClass smpl= new SampleClass();
        Thread t1= new Thread(smpl);
        t1.start();
        System.out.println("Hello");
    }
}

>>> Output
    Hello
    Thread ended

write your code here: Coding Playground