正文

实现 BlockingQueue

(2015-02-03 12:20:07) 下一个

实现 BlockingQueue 的 take() 和 put()


public class BlockingQueueImpl<T> implements BlockingQueue{

    Queue<T> q = new LinkedList<T>();
    int cap = 10;
    long timeOut = 1000;
   
    @Override
    public Object take() {
       
        while(q.isEmpty()){
            try {
                this.wait(timeOut);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Object rst = q.poll();
       
        this.notifyAll();
       
        return rst;
    }

    @Override
    public void put(Object obj) {

        while(q.size()==cap){
            try{
                this.wait(timeOut);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }
       
        q.offer((T) obj);
    }
}

[ 打印 ]
阅读 ()评论 (0)
评论
目前还没有任何评论
登录后才可评论.