java.lang.Runnable
is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. It contains a single method, run()
, which defines the code that constitutes the task.
Key Method in Runnable
run(): This method contains the code that constitutes the task to be executed by the thread.
public interface Runnable {
void run();
}
Implementing Multithreading with Runnable
Step 1: Create a Runnable implementer and implement the run() method.
Step 2: Instantiate the Thread class and pass the implementer to the Thread, Thread has a constructor which accepts Runnable instances.
Step 3: Invoke start() of Thread instance, start internally calls run() 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.
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // Start the thread
}
}