Junior — Middle
How did you implement multithreading in your projects and what problems did you encounter?
sobes.tech AI
Answer from AI
In my projects, I used several approaches to implement multithreading:
- Thread and Runnable — basic Java classes for creating threads.
- ExecutorService — a thread pool for managing and reusing threads.
- Future and Callable — for obtaining results from asynchronous tasks.
- Synchronization (synchronized, Lock) — for managing access to shared resources.
The main issues I encountered:
- Race conditions — when multiple threads modify shared data simultaneously without synchronization.
- Deadlocks — when threads wait for each other, blocking resources.
- Visibility issues — when changes in one thread are not visible to another due to caching.
Example of using ExecutorService:
ExecutorService executor = Executors.newFixedThreadPool(2);
Callable<Integer> task = () -> {
// Some computational task
return 123;
};
Future<Integer> future = executor.submit(task);
try {
Integer result = future.get();
System.out.println("Result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
This approach allows efficient management of threads and obtaining results from asynchronous computations, minimizing synchronization issues.