实现一个简单的阻塞队列

阻塞队列(BlockingQueue)是一个支持两个附加操作的队列。这两个附加的操作是:在队列为空时,获取元素的线程会等待队列变为非空。当队列满时,存储元素的线程会等待队列可用。阻塞队列常用于生产者和消费者的场景,生产者是往队列里添加元素的线程,消费者是从队列里拿元素的线程。阻塞队列就是生产者存放元素的容器,而消费者也只从容器里拿元素。

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

/**
 * Created by Lenovo on 2018/5/17.
 */
public class LinkedBlockingQueue<E> {
    private final int capacity;

    private Lock lock = new ReentrantLock();

    private Condition unfull = lock.newCondition();

    private Condition unEmpty = lock.newCondition();

    private int count;

    private LinkedList<E> queue;

    public LinkedBlockingQueue() throws InterruptedException {
        this(Integer.MAX_VALUE);
    }


    public LinkedBlockingQueue(int capacity) throws InterruptedException {
        this.capacity = capacity;
        queue = new LinkedList<E>();
    }


    public void put(E e) throws InterruptedException {
        lock.lock();
        try {
            while (count == capacity) {
                unfull.await();//阻塞队列已满,等待
            }
            queue.add(e);
            count++;
            unfull.signal();
        } finally {
            lock.unlock();
        }
    }

    public E take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {//队列为空,阻塞
                unEmpty.await();
            }
            E e = queue.pop();
            count--;
            unEmpty.signal();
            return e;
        } finally {
            lock.unlock();
        }
    }

}


阅读更多
文章标签: 阻塞队列 手写
个人分类: java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

实现一个简单的阻塞队列

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭