手搓定长阻塞队列

/**
 * 致敬李二狗先生!
 * @param 
 */
class MyBlockingQueue<T> {
    private Object[] values;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    private Lock lock;
    private Condition notFull;
    private Condition notEmpty;


    /**
     * 构造函数,逻辑是初始化必要属性
     * @param capacity 队列最大容量
     */
    public MyBlockingQueue(int capacity) {
        this.values = new Object[capacity];
        lock = new ReentrantLock();
        notFull = lock.newCondition();
        notEmpty = lock.newCondition();
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == values.length;
    }

    /**
     * 入队操作,如果队列已满则进行阻塞,直到被唤醒
     *
     * @param element 要插入的值
     * @return 是否入队成功
     * @throws InterruptedException
     */
    public boolean offer(T element) throws InterruptedException {
        //空检测
        if (element == null) {
            return false;
        }
        lock.lockInterruptibly();
        try {
            while (isFull()) {
                notEmpty.await();
            }
            values[tail] = element;
            tail = (++tail) % values.length;
            size++;
            notFull.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 出队操作,如果队列为空则进行阻塞,直到被唤醒
     *
     * @return 队头的值
     * @throws InterruptedException
     */
    public T poll() throws InterruptedException {
        lock.lockInterruptibly();
        try {
            while (isEmpty()) {
                notFull.await();
            }
            T res = (T) values[head];

            head = (++head) % values.length;
            size--;
            notEmpty.signal();
            return res;
        } finally {
            lock.unlock();
        }
    }

    public int getSize() {
        return size;
    }
}

你可能感兴趣的:(JAVA)