package tpsema; public class S4 implements Semaphore { protected int n; protected int first; protected int last; protected Thread fifo[]; public static final int MAX_FIFO = 100; S4(int pn) { n = pn; first=last=0; fifo = new Thread[MAX_FIFO]; } public synchronized void P() { if(n<=0 || first != last) { last=(last+1)%MAX_FIFO; fifo[last] = Thread.currentThread(); System.out.println("-> Thread " + Thread.currentThread() + " entering FIFO..."); try { wait(); } catch(InterruptedException e) { System.out.println("## Thread " + Thread.currentThread() + " woken up by exception..."); } if(Thread.currentThread() != fifo[(first+1)%MAX_FIFO]) { System.out.println("!!! Serious error: Thread " + Thread.currentThread() + "is not the first in queue!!!"); System.exit(1); } System.out.println("<- Thread " + Thread.currentThread() + " leaving FIFO..."); first = (first+1)%MAX_FIFO; } n--; } public synchronized void V() { System.out.println("Thread " + Thread.currentThread() + " signaling " + this.toString() + "..."); if(first != last) { System.out.println("Waking up " + fifo[(first+1)%MAX_FIFO] + " with interrupt()..."); fifo[(first+1)%MAX_FIFO].interrupt(); } n++; } }