[LinkedIn面试]implement the take() and put() of blocking queue
题目如下:
public interface BlockingQueue
{
/** Retrieve and remove the head of the queue, waiting if no elements
are present. */
T take();
/** Add the given element to the end of the queue, waiting if necessary
for space to become available. */
void put (T obj);
}
看了网上的解答,很不错的解答,从这里来的:Good Solution (with a little tweak) 其中感觉有点错误,看我在代码中的comment
public class BlockingQueue {
private List queue = new LinkedList();
private int limit = 10;
public BlockingQueue(int limit){
this.limit = limit;
}
public synchronized void enqueue(Object item)
throws InterruptedException {
while(this.queue.size() == this.limit) {
wait();
}
/** This is what comes from the post, but if you notify here, say a 'dequeue()' is waiting, the size would remain at 0 doesn't it? So I would call notify at the end
if(this.queue.size() == 0) {
notifyAll();
}
**/
this.queue.add(item);
notifyAll();
}
public synchronized Object dequeue()
throws InterruptedException{
while(this.queue.size() == 0){
wait();
}
/** This is what comes from the post, but if you notify here, say a 'enqueue()' is waiting, the size would remain at the limit doesn't it? So I would call notify at the end
if(this.queue.size() == this.limit){
notifyAll();
}
**/
Object ret = this.queue.remove(0);
notifyAll();
return ret;
}
}