Junior — Middle
How have you implemented and managed multithreading in your projects?
sobes.tech AI
Answer from AI
In Java projects, I used several approaches to manage multithreading:
- Thread class and Runnable interface — for creating and starting threads.
- ExecutorService — for managing a thread pool, which allows efficient reuse of threads and control over their number.
- Synchronization — using the synchronized keyword or classes from java.util.concurrent (e.g., ReentrantLock) to prevent race conditions.
- Concurrent Collections — such as ConcurrentHashMap for thread-safe collection operations.
- Future and Callable — for obtaining results from asynchronous tasks.
Example of creating and running a task via ExecutorService:
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> {
// task code
System.out.println("Execution in thread " + Thread.currentThread().getName());
});
executor.shutdown();