Kann ich eine blockierende Warteschlange mit Semaphore in Java implementieren?
Ich frage mich, ob es möglich ist, mit Semaphore eine blockierende Warteschlange zu implementieren.
n den folgenden Codes verwende ich ein Semaphor, um den kritischen Abschnitt zu schützen, und zwei weitere Semaphor-Objekte, um die Anzahl der leeren Slots und gefüllten Objekte zu verfolge
public class BlockingQueue {
private List<Object> queue = new LinkedList<Object>();
private int limit;
private Semaphore slots; // semaphore for empty slots
private Semaphore objs; // semaphore for filled slots
private Semaphore mutex; // for the critical section
public BlockingQueue(int limit) {
this.limit = limit;
this.slots = new Semaphore(limit); // initial empty slot = capacity
this.objs = new Semaphore(0);
this.mutex = new Semaphore(1);
}
private void enqueue(Object o) throws InterruptedException {
slots.acquire();
mutex.acquire(); // critical section starts
queue.add(o);
mutex.release(); // critical section ends
objs.release();
}
private Object dequeue() throws InterruptedException {
objs.acquire();
mutex.acquire(); // critical section starts
Object o = queue.remove(0);
mutex.release(); // critical section ends
slots.release();
return o;
}
}