实现一个阻塞队列

class MyBlockingQueue {
    private int[] items = new int[1000];
    private int tail = 0;
    private int head = 0;
    private int size = 0;

    public void put(int elem) throws InterruptedException {
        synchronized (this) {
            while (size == items.length) {
                this.wait();
            }
            items[tail++] = elem;
            tail++;
            if (tail >= items.length) {
                tail = 0;
            }
            size++;
            this.notify();
        }
    }
    public int take() throws InterruptedException {
        synchronized (this) {
            while (size == 0) {
                this.wait();
            }
            int ret = items[head++];
            if (head >= items.length) {
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}

你可能感兴趣的:(java,前端,算法)