Junior — Middle
What tools are available for managing thread or task synchronization in parallel programming?
sobes.tech AI
Answer from AI
In Java, various tools are used for thread synchronization and task management:
-
The
synchronizedkeyword — blocks access to code or objects so that only one thread can execute that section of code at a time. -
Lockobjects fromjava.util.concurrent.locks— a more flexible alternative tosynchronized, for example,ReentrantLockallows explicit locking and unlocking. -
Classes from the
java.util.concurrentpackage:Semaphore— limits the number of threads that can access a resource simultaneously.CountDownLatch— allows one or more threads to wait until other threads complete certain actions.CyclicBarrier— synchronizes groups of threads, making them wait for each other.Exchanger— enables two threads to exchange data.
-
Volatile variables — ensure visibility of variable changes between threads without locks.
-
Atomic classes (
AtomicInteger,AtomicReference, etc.) — provide atomic operations without using locks.
Example of using synchronized:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}