Java实现阻塞队列

public class ArrayBlockQueue {
    public int size;
    private volatile Object[] items;
    private volatile int pollPoint = 0;
    private volatile int addPoint = 0;
    private volatile int count = 0;

    private Object addLock = new Object();
    private Object pollLock = new Object();

    public ArrayBlockQueue(int size) {
        this.size = size;
        this.items = new Object[size];
    }

    public void add(Object item) {
        synchronized (addLock) {
            while (count >= size) {
                try {
                    addLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            items[addPoint] = items;
            addPoint = (addPoint + 1) % size;
            count++;
            if (count == 1) {
                synchronized (pollLock) {
                    pollLock.notifyAll();
                }
            }
        }
    }

    public Object poll() {
        synchronized (pollLock) {
            while (count == 0) {
                try {
                    pollLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Object value = items[pollPoint];
            pollPoint = (pollPoint + 1) % size;
            count--;
            if (count == (size - 1)) {
                synchronized (addLock) {
                    addLock.notifyAll();
                }
            }
            return value;
        }
    }
}

参考链接:https://segmentfault.com/a/1190000020005820?utm_source=tag-newest

posted @ 2020-11-24 17:13  沈云飞  阅读(80)  评论(0)    收藏  举报