我想知道是否可以使用Semaphore來實現阻塞隊列?我可以在Java中使用Semaphore實現阻塞隊列嗎?
在下面的代碼,我使用一個信號量,以保護關鍵部分,和兩個信號量更多的對象跟蹤空時隙和填充的對象的數量。
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;
}
}
爲什麼你想爲[推倒重來(https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html)?順便說一下:信號量不是一個互斥體,也不是一個「關鍵部分」。這兩個條款有完全不同的含義 – specializt
@specializt其實我之前問這個問題的採訪,所以我試圖找出如何自己做。我知道Semaphore不是互斥體,也不是關鍵部分。我只是說我正在使用名爲mutex的Semaphore來保護關鍵部分。對不清楚的描述抱歉。 –
你的代碼中沒有關鍵部分......還有:要求你重新實現已存在的東西的僱主應該不惜一切代價避免......只是說。事實上,尋找那些重新使用久經考驗的穩定庫的員工是可取的,而不是重寫所有內容,因爲這大大加快了開發速度 - 它也提高了軟件質量。 – specializt