ExecutorService in Java

The Java ExecutorService is an interface which is present inside java.util.concurrent package. The ExecutorService interface is a subinterface of the Executor interface. It allows us to execute tasks asynchronously on threads. It allows us to submit tasks for execution. With the help of ExecutorService we can create and manage the pool of Threads, reusing them to execute submitted tasks, which is more efficient than creating a new thread for each task.

Now, let’s understand ExecutorService with an example.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Car {

     public static void main(String[] args) {
		
	System.out.println("Project For Develop Car");
	System.out.println();
		
	ExecutorService productManager = Executors.newFixedThreadPool(3);
		
	        productManager.submit(() -> {
		  System.out.println("Task - 1");
		  System.out.println("Blueprint(Design) of car is           created successfully, By :- "+Thread.currentThread().getName());
		  System.out.println();
		});
	
		productManager.submit(() -> {
		  System.out.println("Task - 2");
		  System.out.println("Assemble Parts of cars is successfully, By :- "+Thread.currentThread().getName());
		  System.out.println();
		});

		productManager.submit(() -> { 
		  System.out.println("Task - 3");
	      System.out.println("Testing of car is successfully, By :- "+Thread.currentThread().getName());
	      System.out.println();
		});

	}
}

Output:-

Project For Develop Car 
Task - 1
Blueprint(Design) of car is created successfully, By :-pool-1-thread-1 
Task - 2 
Assemble Parts of cars is successfully, By :- pool-1-thread-2 
Task - 3
Testing of car is successfully, By :- pool-1-thread-3 

In above program

ExecutorService productManager = Executors.newFixedThreadPool(3);

This line creates an ExecutorService named productManager with a fixed pool of 3 threads. An ExecutorService manages the execution of tasks on multiple threads.

productManager.submit(() -> {
    System.out.println("Task - 1");
    System.out.println("Blueprint(Design) of car is created             successfully, By :- " + Thread.currentThread().getName());
    System.out.println();
});

These lines submit tasks to the productManager ExecutorService. Each task is represented as a lambda expression and contains code to print information about different stages of car development.

Leave a Reply

Your email address will not be published. Required fields are marked *

*