Junior — Middle
What tools does the Java standard library provide for working with threads and parallelism?
sobes.tech AI
Answer from AI
Java's standard library provides several tools for working with threads and concurrency:
- Thread class — the basic way to create and manage threads.
- Runnable and Callable interfaces — for defining tasks that can run in threads.
- Executor Framework (java.util.concurrent.Executor, ExecutorService) — abstraction for managing thread pools and executing tasks asynchronously.
- Future and CompletableFuture — for obtaining results of asynchronous computations and chaining them.
- Synchronizers (CountDownLatch, Semaphore, CyclicBarrier, Phaser) — for thread coordination.
- Concurrent Collections (ConcurrentHashMap, CopyOnWriteArrayList, etc.) — thread-safe collections.
- Fork/Join Framework — for efficient parallelization of tasks, especially recursive ones.
Example of using ExecutorService:
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task executed in thread " + Thread.currentThread().getName()));
executor.shutdown();