![]() |
VOOZH | about |
The Executor interface in Java provides a high-level mechanism to execute tasks asynchronously without directly managing threads. It acts as a replacement for manually creating and controlling Thread objects. Executors submit Runnable tasks for execution and manage the underlying threads efficiently.
public interface Executor {
void execute(Runnable command);
}
Thread executed under an executor
Explanation: ExecutorImp implements the Executor interface and overrides execute() to run the task in a new thread. When execute() is called, the NewThread task runs and prints the message.
These are the common classes that implement Executor or its sub-interfaces to provide thread pooling and scheduling features.
The Executor interface has two main sub-interfaces that extend its functionality:
1. ExecutorService
2. ScheduledExecutorService
ExecutorService to allow scheduling tasks with a delay or at fixed intervals.execute(Runnable command): Submits a task for execution. The task may run in a new thread, a thread pool, or the calling thread.
Task 1 executed Task 2 executed Task 3 executed
Explanation: SimpleExecutor implements the Executor interface and overrides execute() to start each submitted task in a new thread. We submit three tasks using lambda expressions, and each prints a message asynchronously.