The Runnable interface in Java is an interface that should be implemented by any class whose instances are intended to be executed by a thread. The interface defines a single method called run()
, which is executed when the thread is started. There are two ways to start a new thread in Java: subclassing Thread and implementing Runnable. When a task can be done by overriding only the run()
method of Runnable, there is no need to subclass Thread. To create a new thread using Runnable, you need to follow these steps:
- Create a Runnable implementer and implement the
run()
method. - Instantiate the Thread class and pass the implementer to the Thread. Thread has a constructor which accepts Runnable instances.
- Invoke
start()
of Thread instance.start()
internally callsrun()
of the implementer.
Invoking start()
creates a new Thread that executes the code written in run()
. Calling run()
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.
The most common use case of the Runnable interface is when we want only to override the run()
method. When a thread is started by the object of any class which is implementing Runnable, then it invokes the run()
method in the separately executing thread. A class that implements Runnable runs on a different thread without subclassing Thread as it instantiates a Thread instance and passes itself in as the target. This becomes important as classes should not be subclassed unless there is an intention of modifying or enhancing the fundamental behavior of the class.
In summary, the Runnable interface is used to execute code on a concurrent thread in Java. It is an interface that should be implemented by any class whose instances are intended to be executed by a thread.