阻塞队列

阻塞队列与普通队列的区别在于,当队列是空的时,从队列中获取元素的操作将会被阻塞,或者当队列是满时,往队列里添加元素的操作会被阻塞。试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其他的线程往空的队列插入新的元素。同样,试图往已满的阻塞队列中添加新元素的线程同样也会被阻塞,直到其他的线程使队列重新变得空闲起来,如从队列中移除一个或者多个元素,或者完全清空队列,下图展示了如何通过阻塞队列来合作:

线程1往阻塞队列中添加元素,而线程2从阻塞队列中移除元素

从5.0开始,JDK在java.util.concurrent包里提供了阻塞队列的官方实现。尽管JDK中已经包含了阻塞队列的官方实现,但是熟悉其背后的原理还是很有帮助的。

阻塞队列的实现方式1

使用传统的wait,notifyall方式实现

import java.util.LinkedList;
import java.util.List;

public class BlockingQueue {
    private List list = new LinkedList();
    private int limit = 10;
    private static BlockingQueue queue = new BlockingQueue();
    public synchronized void enqueue(Object item) throws InterruptedException {
        while (list.size() == limit) {
            wait();
        }
        this.list.add(item);
        notifyAll();
    }

    public synchronized void dequeue() throws InterruptedException {
        if (this.list.size() == 0) {
            wait();
        }
        this.list.remove(0);
        notifyAll();
    }
}

阻塞队列的实现方式2

使用传统的ReentrantLock方式实现

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

class BoundedBuffer{
    final Lock        lock        = new ReentrantLock();
    final Condition    notFull        = lock.newCondition();
    final Condition    notEmpty    = lock.newCondition();

    final Object[]    items        = new Object[100];
    int  putptr, takeptr, count;

    public void put(Object x) throws InterruptedException{
        lock.lock();
        try{
            while (count == items.length){
                notFull.await();
            }
            items[putptr] = x;
            if(++putptr == items.length){
                putptr = 0;
            }
            ++count;
            notEmpty.signal();
        }
        finally{
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException{
        lock.lock();
        try{
            while (count == 0){
                notEmpty.await();
            }
            Object x = items[takeptr];
            
            if(++takeptr == items.length){
                takeptr = 0;
            }
            --count;
            notFull.signal();
            return x;
        }
        finally{
            lock.unlock();
        }
    }
}
原文地址:https://www.cnblogs.com/pingh/p/3756191.html