The ExecutorService class in Java provides a way to execute a batch of tasks concurrently. It provides a way to manage and control the lifecycle of multiple threads in a more efficient and easier way. The ExecutorService interface extends the Executor interface and provides additional methods to manage the lifecycle of threads.
To use the ExecutorService class, you first need to create an instance of it using the Executors factory class. The Executors class provides various factory methods to create instances of ExecutorService. Here’s an example that creates a fixed thread pool with a maximum of 10 threads:
ExecutorService executor = Executors.newFixedThreadPool(10);
Once you have created an instance of ExecutorService, you can submit tasks to it using the submit() method. The submit() method takes a Callable or Runnable object as an argument and returns a Future object, which can be used to obtain the result of the task.
Here’s an example that submits a Runnable task to the executor:
executor.submit(new Runnable() {
public void run() {
System.out.println("Task executed by thread "
+ Thread.currentThread().getName());
}
});
In this example, we submit a Runnable task to the executor. The run() method of the Runnable object is executed by one of the threads in the pool.
Once you have submitted all the tasks to the executor, you can shut it down using the shutdown() method. The shutdown() method initiates an orderly shutdown of the executor, which means that it will wait for all the currently executing tasks to finish before shutting down.
executor.shutdown();
In conclusion, the ExecutorService class in Java provides a way to execute a batch of tasks concurrently in a more efficient and easier way. It provides a way to manage and control the lifecycle of multiple threads, and provides additional methods to manage the lifecycle of threads. It is a very useful and powerful class in Java’s concurrency framework.