I have an example of a repeated semaphore, but it is intended for only 2 applicants. If you want to extend the code by more than 2, you must implement a simple list and make some changes, including the test for wait()
in the aquire()
method.
package nmscd.utils; public class SimpleSemaphore { private boolean aquired = false; private Thread currThread; private Thread releasedThread; private int pretendersCount = 0; public synchronized void aquire() throws InterruptedException { while ((Thread.currentThread() != currThread && aquired) || (pretendersCount > 0 && Thread.currentThread() == releasedThread)) { pretendersCount++; try { wait(); } finally { pretendersCount--; } } aquired = true; currThread = Thread.currentThread(); } public synchronized void release() { if (Thread.currentThread() == currThread) { aquired = false; currThread = null; releasedThread = Thread.currentThread(); notifyAll(); } } }
The key in this class is to check in the aquire method to find out if the thread you want is needed, all other threads must wait. Therefore, if you have enough information to determine this stream, you can choose which stream is returned from aquire()
source share