正文

實現 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)
評論
目前還沒有任何評論
登錄後才可評論.