The Runnable interface in Java is a functional interface used to represent a task that can be executed concurrently, typically in a separate thread. It is part of the java.lang package and is central to Java’s concurrency framework.
public interface Runnable {
public abstract void run();
}
Code language: PHP (php)
Usage
- Implementing Runnable: You can create a class that implements Runnable and override the run() method.
class MyTask implements Runnable {
public void run() {
System.out.println("Task is running in thread: " + Thread.currentThread().getName());
}
}
Code language: PHP (php)
  2. Running a Runnable:
- Using a Thread
Runnable task = new MyTask();
Thread thread = new Thread(task);
thread.start(); // Starts the thread and calls run()
Code language: JavaScript (javascript)
- Â Â Using Lambda Expression (Java 8+)
Runnable task = () -> System.out.println("Task is running in thread: " + Thread.currentThread().getName());
new Thread(task).start();
Code language: JavaScript (javascript)
After creating the Thread object, you can start the thread’s execution by calling the start() method. It internally calls the run() method of the Runnable object.
thread.start();
Code language: CSS (css)
By implementing the Runnable interface, you can separate the task or code that will be executed by a thread from the thread itself. This allows for better separation of concerns and promotes more flexible and reusable code.