In Java, a thread pool is a collection of worker threads that are managed by a thread pool manager. The thread pool manager is responsible for creating and managing the worker threads, which are used to perform tasks in the application.
When a task needs to be performed, it is submitted to the thread pool. The thread pool manager assigns the task to an available worker thread in the pool, which then executes the task. Once the task is completed, the worker thread is returned to the thread pool and made available to perform another task.
Thread pools are useful in multi-threaded applications because they allow tasks to be performed concurrently without creating a large number of threads. By reusing existing threads in the pool, the application can avoid the overhead of creating and destroying threads for each task.
Here’s an example of how to create and use a thread pool in Java:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("Task " + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("All tasks completed");
}
}
class WorkerThread implements Runnable {
private String task;
public WorkerThread(String task) {
this.task = task;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()
+ " executing " + task);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " completed " + task);
}
}
In this example, we create a fixed-size thread pool with five worker threads using the Executors.newFixedThreadPool() method. We then submit ten tasks to the thread pool using the execute() method, which assigns each task to an available worker thread in the pool.
The WorkerThread class defines the task that will be performed by each worker thread. In this case, the task simply prints a message to indicate that it is executing the task, sleeps for one second, and then prints a message to indicate that it has completed the task.
Once all tasks have been submitted to the thread pool, we call the shutdown() method to stop accepting new tasks and wait for all tasks to complete using the isTerminated() method. Once all tasks have completed, we print a message to indicate that all tasks have been completed.
Overall, a thread pool is a powerful tool for managing worker threads in a multi-threaded application. By reusing existing threads in the pool, the application can perform tasks concurrently without creating a large number of threads, improving the efficiency and performance of the application.