Junior — Middle
What tools and methods did you use when implementing multithreading in your projects?
sobes.tech AI
Answer from AI
In Java projects, I used several approaches to implement multithreading:
- The Thread class and the Runnable interface for creating and starting threads.
- ExecutorService from the java.util.concurrent package for managing thread pools, which allows efficient reuse of threads and control over their number.
- Synchronization using the synchronized keyword and classes from java.util.concurrent.locks (e.g., ReentrantLock) to protect shared resources.
- Use of atomic classes (AtomicInteger, AtomicBoolean) for lock-free operations.
- High-level constructs such as CountDownLatch, Semaphore, CyclicBarrier for thread coordination.
Example of creating and starting a thread using ExecutorService:
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> {
System.out.println("Executing task in thread " + Thread.currentThread().getName());
});
executor.shutdown();