Senior
Have you worked with multithreading? What did you use?
sobes.tech AI
Answer from AI
Yes, I have worked with multithreading in Java. For implementation, I used:
- Classes from the
java.util.concurrentpackage — for example,ExecutorServiceto manage thread pools. - Synchronization using the
synchronizedkeyword andReentrantLockclasses to protect shared resources. - Concurrent Collections — such as
ConcurrentHashMap, to avoid issues with concurrent access. - Future and Callable for asynchronous task execution with the ability to obtain results.
Example of creating a thread pool and running a task:
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> {
// task code
System.out.println("Executing in a separate thread");
});
executor.shutdown();
Using these tools allows for efficient and safe multithreading in Java.