Sobes.tech
Junior — Middle

What is the difference between using ExecutorService and creating new threads via the Thread class?

sobes.tech AI

Answer from AI

The use of ExecutorService in Java differs from directly creating threads via the Thread class in the following ways:

  • Thread pool management: ExecutorService allows creating a pool of threads and reusing them to execute multiple tasks, reducing the overhead of creating and destroying threads.
  • Lifecycle management: ExecutorService provides methods for proper shutdown, waiting for tasks to complete, and managing task queues.
  • Simplified code: Instead of manually creating and starting threads, you can simply submit tasks to ExecutorService, which will distribute them across threads.

Example:

ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> {
    System.out.println("Task is running in the thread pool");
});
executor.shutdown();

In contrast, when using Thread, you need to create and start each thread manually, which is less efficient and more cumbersome.