In this Runnable tutorial, we will implement a Java's Runnable Interface.

Runnable interface in Java
A Runnable is basically a type of class
(Runnable is an Interface
) that can be put into a thread, describing what the thread is supposed to do. The java.lang.Runnable
is an interface that is to be implemented by the class whose instances are intended to be executed by a thread. There are two ways to start a new Thread – Subclass Thread and implements the Runnable interface. There is no need for subclassing Thread when the task can be done by overriding only run()
method of Runnable.
See the syntax interface.
class <class> implements <interface>
The Runnable Interface requires of the class to implement the method run() like so:
public class MyRunnableTask implements Runnable {
public void run() {
// do stuff here
}
}
And then use it like this:
Thread t = new Thread(new MyRunnableTask());
t.start();
If you did not have the Runnable interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run()
method in your class, so you could get errors. That is why you need to implement the interface.
Runnable code example:
-
Input
Output shows two active threads in the program – main thread and Thread-0, main method is executed by the Main thread but invoking start on RunnableImpl creates and starts a new thread – Thread-0
How did it work?
- Created a Runnable implementer and implement
run()
method. - Instantiated a Thread class and pass the implementer to the Thread, Thread has a constructor which accepts Runnable instance.
- Invoked
start()
of Thread instance, start internally callsrun()
of the implementer. Invokingstart()
, created a new Thread which executed the code written inrun()
. Note: Callingrun()
directly doesn’t create and start a new Thread, it will run in the same thread. - To start a new line of execution, call
start()
on the thread.
Java Runnable can be used without even making a new Thread. It's basically your basic interface with a single method, run()
that can be called. If you make a new Thread with runnable as it's parameter, it will call the run()
method in a new Thread.
However, there are differences between Thread class and Runnable interface based on their performance, memory usage, and composition.
- By extending thread, there is overhead of additional methods, i.e. they consume excess or indirect memory, computation time, or other resources.
- Since in Java, we can only extend one class, and therefore if we extend Thread class, then we will not be able to extend any other class. That is why we should implement Runnable interface to create a thread.
- Runnable makes the code more flexible as, if we are extending a thread, then our code will only be in a thread whereas, in case of runnable, one can pass it in various executor services, or pass it to the single-threaded environment.
- Maintenance of the code is easy if we implement the Runnable interface.