import java.util.concurrent.Semaphore; class Worker implements Runnable { private Semaphore sem; private int id; public Worker(Semaphore sem, int id) { this.sem = sem; this.id = id; } public void run() { for (int i = 0; i < 5; i++) { // Limit execution to 5 iterations try { sem.acquire(); // Acquire semaphore System.out.println("Thread " + id + " in Critical Section!"); Thread.sleep(500); // Simulate critical section work sem.release(); // Release semaphore System.out.println("Thread " + id + " out of Semaphore!"); Thread.sleep(500); // Simulate non-critical section work } catch (InterruptedException e) { System.out.println("Thread " + id + " interrupted."); } } } } public class Main { public static void main(String args[]) { Semaphore sem = new Semaphore(1); Thread[] bees = new Thread[5]; // Create and start 5 worker threads for (int i = 0; i < 5; i++) { bees[i] = new Thread(new Worker(sem, i + 1)); bees[i].start(); } } }