The Executor framework is a built-in Java framework that simplifies the process of managing worker threads in a multi-threaded application. It provides a standard way of submitting tasks to a pool of threads, allowing tasks to be performed concurrently without creating a large number of threads.
To use the Executor framework, you first need to define the tasks that will be performed by the worker threads. This can be done by implementing the Runnable interface, which defines a single method called run() that contains the code to be executed by the thread.
Hereβs an example of how to use the Executor framework to manage threads in Java:
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorExample {
public static void main(String[] args) {
Executor executor = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 10; i++) {
Task task = new Task("Task " + i);
executor.execute(task);
}
((ExecutorService) executor).shutdown();
while (!executor.isTerminated()) {
}
System.out.println("All tasks completed");
}
}
class Task implements Runnable {
private String taskName;
public Task(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println("Executing " + taskName + " by "
+ Thread.currentThread().getName());
}
}
In this example, we create a fixed-size thread pool with three worker threads using the Executors.newFixedThreadPool() method. We then submit ten tasks to the thread pool using the execute() method, which assigns each task to an available worker thread in the pool.
The Task class defines the task that will be performed by each worker thread. In this case, the task simply prints a message to indicate that it is executing the task and identifies the thread executing the task.
Once all tasks have been submitted to the thread pool, we call the shutdown() method to stop accepting new tasks and wait for all tasks to complete using the isTerminated() method. Once all tasks have completed, we print a message to indicate that all tasks have been completed.
Overall, the Executor framework is a powerful tool for managing worker threads in a multi-threaded application. By providing a standard way of submitting tasks to a pool of threads, the Executor framework simplifies the process of managing worker threads and improves the efficiency and performance of the application.