How does a semaphore manage synchronization and waiting for multiple threads to finish?
sobes.tech AI
Answer from AI
A semaphore in Java is a synchronization mechanism that manages access to a limited number of resources or controls the number of threads executing simultaneously. It contains a counter that decreases when a semaphore is acquired and increases when released.
If the counter is zero, threads attempting to acquire will block and wait until another thread releases. Thus, a semaphore allows limiting the number of threads executing a critical section and organizing the waiting for multiple threads to complete.
Example of using a semaphore to limit concurrent access to a resource:
import java.util.concurrent.Semaphore;
Semaphore semaphore = new Semaphore(3); // maximum 3 threads at the same time
void accessResource() {
try {
semaphore.acquire(); // acquire semaphore
// critical section
System.out.println(Thread.currentThread().getName() + " has access");
Thread.sleep(1000); // simulate work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
semaphore.release(); // release semaphore
System.out.println(Thread.currentThread().getName() + " released access");
}
}
Thus, the semaphore manages synchronization by blocking threads when the limit is reached and unlocking them as resources are released, allowing proper waiting and termination of thread work.