import java.util.concurrent.Semaphore; public class SemaphoreExample { // Semaphore with 3 permits private static final Semaphore semaphore = new Semaphore(3); static class SharedResource { public void use() { try { System.out.println(Thread.currentThread().getName() + " is using the resource."); Thread.sleep(1000); // Simulating resource use } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { System.out.println(Thread.currentThread().getName() + " is done using the resource."); } } } static class Task implements Runnable { private SharedResource resource; public Task(SharedResource resource) { this.resource = resource; } @Override public void run() { try { // Acquiring the semaphore semaphore.acquire(); resource.use(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { // Releasing the semaphore semaphore.release(); } } } public static void main(String[] args) { SharedResource resource = new SharedResource(); // Creating and starting five threads for (int i = 0; i < 5; i++) { new Thread(new Task(resource), "Thread " + (i + 1)).start(); } } }