[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;

  }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值