Junior — Middle
What task is solved using a thread pool and how is it used in programming?
sobes.tech AI
Answer from AI
A thread pool is used to manage a set of threads that are reused to execute multiple tasks. This avoids the overhead of creating and destroying threads for each task, which improves performance and reduces system load.
In programming, a thread pool is created once, and then tasks are queued. An available thread from the pool takes a task from the queue and executes it. After completion, the thread returns to the pool and is ready for the next task.
Example in Java:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("Executing task in thread pool");
});
executor.shutdown();
Here, a pool of 5 threads is created, and the task is executed by one of them.