自己实现阻塞队列(基于数组)

public class MyBlockQueue {

    private int count;

    private int head;

    private int tail;

    private String[] arr;

    public MyBlockQueue(int arrLen) {
        this.count = 0;
        this.head = 0;
        this.tail = 0;
        arr = new String[arrLen];
    }

    public synchronized void put(String data) {
        while (count >= arr.length) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        arr[tail] = data;
        this.tail = (tail + 1) % arr.length;
        count++;
        notifyAll();
    }

    public synchronized String take() {
        while (count <= 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String str = arr[head];
        this.head = (head + 1) % arr.length;
        count--;
        notifyAll();
        return str;
    }

    public synchronized int size() {
        return arr.length;
    }

}

猜你喜欢

转载自www.cnblogs.com/moris5013/p/10911212.html