[LinkedIn面试]implement the take() and put() of blocking queue
来源:互联网 发布:内控优化演讲 编辑:程序博客网 时间:2024/05/22 11:46
题目如下:
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; }}
0 0
- [LinkedIn面试]implement the take() and put() of blocking queue
- Blocking Queue
- Take care of the Details
- Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms
- Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms
- java-Queue的add/offer/put,remove/poll/take,element/peek异同
- [LinkedIn] Implement a Semaphore
- gotoAndPlay and the queue
- the implement of system function.
- Mix of blocking and non-blocking assignments to variable <en> is not a recommended coding practice.
- non-blocking and blocking mode
- queue implement
- [LinkedIn]Implement Find and replace (find given pattern and replace it with a given string)
- LeeCode-Sqrt(x)Implement int sqrt(int x). Compute and return the square root of x.
- usage of stack and queue
- Nothing in the world can take the place of Persistence
- Design the queue of java
- The implementation of multiprocess.Queue
- /proc/pid下的相应信息说明
- 第11课时,自测
- 如何创建线程进程 转载
- 2016级阿里实习生java电话面试题
- [HiHoCoder]二分·归并排序之逆序对
- [LinkedIn面试]implement the take() and put() of blocking queue
- sed: -e expression #1, char 103: unknown option to `s'
- 爬虫学习笔记
- 智能指针实现
- 判断日期格式
- 如何实现PDF转换为PPT幻灯片格式
- 程序自动化需要一个Windows服务
- extjs3 RadioGroup单选变多选问题
- java.lang.NoClassDefFoundError: org/apache/poi/xssf/usermodel/XSSFWorkbook 错误来源