Both the Java Semaphore and CountDownLatch classes are used in multi-threaded programming to control the execution of threads. However, they have different use cases and implementations.
The Java Semaphore class is used to control access to a limited set of resources. It allows a specified number of threads to access the resources at any given time, while blocking other threads that try to access the resources when they are not available. The Semaphore maintains a count of the available resources, and each time a thread acquires a resource, the count is decremented. When the count reaches zero, all subsequent requests for the resource are blocked until a resource becomes available again.
Here is an example of using Semaphore in Java:
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3); // allows 3 threads to access a resource
for (int i = 1; i <= 6; i++) {
Thread thread = new Thread(new Worker(semaphore, i));
thread.start();
}
}
static class Worker implements Runnable {
private Semaphore semaphore;
private int id;
public Worker(Semaphore semaphore, int id) {
this.semaphore = semaphore;
this.id = id;
}
public void run() {
try {
semaphore.acquire();
System.out.println("Worker " + id + " acquired the resource.");
Thread.sleep(1000); // simulate work
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
System.out.println("Worker " + id + " released the resource.");
}
}
}
}
In this example, we create a Semaphore object with a limit of 3 resources that can be accessed concurrently. We then create 6 Worker threads, each of which tries to acquire the semaphore by calling the acquire() method. If there are less than 3 threads currently holding the semaphore, the Worker thread is allowed to proceed and execute its task. Otherwise, it blocks until a resource becomes available. After executing its task, the Worker thread releases the semaphore by calling the release() method, allowing other threads to acquire the resource.
The Java CountDownLatch class, on the other hand, is used to synchronize the execution of multiple threads. It allows one or more threads to wait until a set of operations has been completed by other threads. The CountDownLatch maintains a count of the number of operations that need to be completed, and each time an operation is completed, the count is decremented. When the count reaches zero, all threads waiting on the CountDownLatch are released.