![]() |
VOOZH | about |
The Runnable interface is part of the java.lang package and is used to define a task that can be executed by a thread. It provides a way to achieve multithreading by separating the task logic from the thread execution mechanism.
Example: Implementing Runnable
Thread is running using Runnable interface
Explanation:
public interface Runnable {
void run();
}
Create a class that implements the Runnable interface and override the run() method to define the task to be executed by the thread.
Create a Thread object by passing the Runnable instance and call start() to execute the task in a new thread.
Since Runnable is a functional interface, it can be written using lambda expressions.
Thread running using lambda
Explanation: This code creates a Runnable using a lambda expression, where the lambda body represents the run() method logic. The Runnable is passed to a Thread object, and calling start() creates a new thread that executes the code inside the lambda.
The Executor Framework provides a high-level API for managing threads efficiently. Instead of creating threads manually, tasks are submitted to a thread pool.
Task executed by Executor
Explanation:
In Java, exceptions in a Runnable must be handled inside the run() method because run() cannot throw checked exceptions. If not handled, the exception terminates the thread.
Exception handled inside Runnable
Explanation:
| Point | Runnable Interface | Thread Class |
|---|---|---|
| Type | It is an interface used to define a task. | It is a class used to create and control a thread. |
| Inheritance | Allows a class to extend another class. | Does not allow extending any other class. |
| Code Reusability | Provides better reusability by separating task logic. | Less reusable as task and thread are tightly coupled. |
| Memory Usage | Uses less memory as threads are created separately. | Uses more memory due to thread inheritance. |
| Preferred Usage | Recommended for multithreading. | Less preferred compared to Runnable. |