算法-03-Java 实现阻塞队列 字节三面算法题

package com.example.polaris;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BlockedQueue<T> {
    private int size;
    private Object[] queue;

    final Lock lock = new ReentrantLock();
    // 条件变量:队列不满
    final Condition notFull = lock.newCondition();
    // 条件变量:队列不空
    final Condition notEmpty = lock.newCondition();

    private int index;
    private int removeIndex;
    private int currLen;


    public BlockedQueue(int size) {
        this.index = 0;
        this.removeIndex = 0;
        this.currLen = 0;
        this.size = size;
        queue = new Object[size];
    }

    // 入队
    public void push(T element) throws InterruptedException {
        lock.lock();
        try {
            while (currLen == size) {
                System.out.println("队列已满,等待队列不满");
                notFull.await();
            }
            queue[index] = element;
            if (++index == size) {
                index = 0;
            }
            currLen++;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    // 出对
    public T pop() throws InterruptedException {
        lock.lock();
        try {
            while (currLen == 0) {
                System.out.println("队列已空,等待队列不空");
                notEmpty.await();
            }
            Object obj = queue[removeIndex];
            if (++removeIndex == size) {
                removeIndex = 0;
            }
            currLen--;
            notFull.signal();
            return (T) obj;
        } finally {
            lock.unlock();
        }
    }

}

 

posted @ 2021-07-19 23:02  sixinshuier  阅读(40)  评论(0编辑  收藏  举报