Sobes.tech
Senior

Kas teil oli vaja kasutada java.util.concurrent klasse?

sobes.tech AI

Vastus AI-lt

Yes, in my practice I have often used classes from the java.util.concurrent package to solve tasks related to multithreading and synchronization.

For example:

  • ExecutorService for managing thread pools and executing tasks asynchronously.
  • ConcurrentHashMap for thread-safe access to collections without locks.
  • CountDownLatch and CyclicBarrier for thread coordination.
  • Semaphore to limit the number of operations performed simultaneously.

Example of using ExecutorService:

ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
    int taskId = i;
    executor.submit(() -> {
        System.out.println("Task " + taskId + " is running");
    });
}
executor.shutdown();

Using these classes allows writing efficient, scalable, and safe code in a multithreaded environment.