Wednesday, July 23, 2014

Concurrent - 实现一个blocking queue

这是Java Condition里给的示例代码,若是用linkedlist实现会更简单些。
class BlockingQueue{
    final Lock lock = new ReentrantLock();
    final Condition notFull = lock.newCondition();//两个Condition
    final Condition notEmpty = lock.newCondition();
    
    final Object[] items;
    int putptr, takeptr, count;
    public BlockingQueue(int capacity){//construct function, 初始化buffer的capacity
        items = new Object[capacity];
    }
    
    public void put(Object x){//put 方法
        lock.lock();
        try{
            while(count==items.length)//count代表现在buffer的size
                notFull.await();
            items[putptr] = x;
            if(++putptr == items.length)//若存满,则从头开始,若用linkedlist结构就不需要这一步了。
                putptr = 0;
            count++;
            notEmpty.signal();
        }catch(InterruptedException e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }
    public Object take(){//take 方法
        lock.unlock();
        try{
            while(count==0)
                notEmpty.await();
            Object x = items[takeptr];
            if(++takeptr == items.length)
                takeptr = 0;
            count--;
            notFull.signal();
            return x;
        }catch(InterruptedException e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
        return null;
    }  
}

No comments:

Post a Comment