Senior
What is the difference between creating a thread via ExecutorService and via new Thread?
sobes.tech AI
Answer from AI
The main difference between creating a thread via new Thread() and using ExecutorService lies in managing the lifecycle and scalability:
-
new Thread() creates a new thread directly. It's simple but inefficient for a large number of tasks, as each thread consumes OS resources, and creating/deleting threads is costly.
-
ExecutorService is a high-level API for managing a thread pool. It allows reusing threads, managing task queues, controlling the number of concurrently running threads, and shutting down properly.
Example of using ExecutorService:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
// task
});
executor.shutdown();
Using ExecutorService is preferable in production code for efficient multithreading management, resource leak prevention, and performance enhancement.