Junior — Middle
How can task sending and waiting for their completion be organized using ThreadPoolExecutor?
sobes.tech AI
Answer from AI
To organize task submission and wait for their completion using ThreadPoolExecutor in Java, you can use the following approach:
- Create an instance of ThreadPoolExecutor via Executors.newFixedThreadPool or another factory method.
- Submit tasks for execution using the submit() method, which returns a Future object.
- To wait for task completion, call the get() method on the Future object.
Example:
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(3);
Callable<String> task = () -> {
Thread.sleep(1000);
return "Task completed";
};
Future<String> future = executor.submit(task);
// Wait for task completion and get the result
String result = future.get();
System.out.println(result);
executor.shutdown();
}
}
Thus, you can submit multiple tasks and, if necessary, wait for their completion using Future objects.