Java Thread Pool
A thread pool
in Java is a collection of worker threads that are managed by a pool manager.
Thread pools are used to efficiently execute a large number of tasks
concurrently. Creating a new thread for each task can be expensive, so thread
pools help manage and reuse threads, improving performance and resource
utilization.
Java provides
the Executor framework and the ExecutorService interface to work with thread
pools. The Executors class provides factory methods to create different types
of thread pools.
Advantage of
Java Thread Pool
Better performance
It saves time because there is no need to create a new thread.
Example 01:
package com.java.Multi_threading;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
// Create a fixed-size thread pool with 3 threads
ExecutorService executorService = Executors.newFixedThreadPool(3);
// Submit tasks to the thread pool
for (int i = 1; i <= 5; i++) {
Runnable task = new Task("Task " + i);
executorService.submit(task);
}
// Shutdown the thread pool
executorService.shutdown();
}
}
class Task implements Runnable {
private String taskName;
public Task(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println("Executing " + taskName + " on Thread: " + Thread.currentThread().getName());
}
}
0 Comments