Junior — Middle
How to organize task execution using ThreadPoolExecutor?
sobes.tech AI
Answer from AI
To perform a task using ThreadPoolExecutor in Java, you need to create a thread pool and submit tasks to it for execution. This allows efficient management of the number of threads running simultaneously and reusing them.
Example:
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) {
// Create a pool of 3 threads
ExecutorService executor = Executors.newFixedThreadPool(3);
Runnable task = () -> {
System.out.println("Task is running in thread " + Thread.currentThread().getName());
};
// Submit tasks to the pool
for (int i = 0; i < 5; i++) {
executor.submit(task);
}
// Shutdown the pool
executor.shutdown();
}
}
Here, Executors.newFixedThreadPool creates a pool with a fixed number of threads. The submit method adds tasks to the execution queue. After calling shutdown, the pool stops accepting new tasks but completes the already running ones.