Junior — Middle
Which class from the java.util.concurrent package would you use to organize multithreaded file operations?
sobes.tech AI
Answer from AI
To organize multithreaded file operations in Java, the ExecutorService class from the java.util.concurrent package is often used. It allows managing a thread pool and executing tasks asynchronously.
Example of usage:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
ExecutorService executor = Executors.newFixedThreadPool(4); // pool of 4 threads
executor.submit(() -> {
// code to process the file
System.out.println("Processing file in thread " + Thread.currentThread().getName());
});
executor.shutdown();
Also useful classes include:
Future— for obtaining the result of an asynchronous operation.Callable— for tasks that return a result.
Thus, ExecutorService is the main tool for organizing multithreaded processing, allowing efficient management of threads and tasks.