BlockingQueue的实现、使用 以及 生产者消费者的BlockingQueue实现

本文介绍了BlockingQueue接口的主要实现,包括ArrayBlockingQueue和LinkedBlockingQueue,并详细解析了BlockingQueue的使用,如offer、put、poll和take方法。此外,还展示了如何在生产者消费者模式下应用BlockingQueue,通过Producer和Consumer的角色实现线程间的同步与通信。

BlockingQueue

  • BlockingQueue接口主要实现:

这里写图片描述

  • 主要有ArrayBlockingQueue(基于数组,有界队列)LinkedBlockingQueue(无界队列)
  • 关键是在Blocking上,它会让服务线程在队列为空时,进行等待,当有新的消息进入队列后,自动将线程唤醒。
BlockingQueue的实现与使用
  • ArrayBlockingQueue的内部元素都放在一个对象数组中,final Object[] items;
  • 压入元素:offer()-如果队列满了,返回false; put()-如果队列满了,它会一致等待,直到有空闲的位置。
  • 弹出元素:poll()-如果队列为空直接返回null,take()-会等到队列中有可用元素。
  • 使用 put() , take()
  • 底层实现: 通过以下字段实现put(), take()
    // 1.字段
    /** Main lock guarding all access */
    final ReentrantLock lock;

    /** Condition for waiting takes */
    private final Condition notEmpty;

    /** Condition for waiting puts */
    private final Condition notFull;
  • put(), taker()
    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }
    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

生产者消费者的BlockingQueue实现

  • Producer:
public class Producer implements Runnable{
    BlockingQueue<String> queue;

    public Producer(BlockingQueue<String> queue){
        this.queue = queue;
    }

    @Override
    public void run() {
        try{
            String product_name = "a product-"+Thread.currentThread().getName();
            System.out.println("I have produced:"+Thread.currentThread().getName());
            queue.put(product_name); //如果队满,则阻塞
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
  • Consumer:
public class consumer implements Runnable{
    BlockingQueue<String> blockingQueue;

    public consumer(BlockingQueue<String> blockingQueue){
        this.blockingQueue = blockingQueue;
    }


    @Override
    public void run() {
        try {
            String product_name = blockingQueue.take(); //如果队空,则阻塞
            System.out.println("消费了:"+product_name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • test:
public class test_producer {

    public static void main(String[] args) {
        BlockingQueue<String> queue = new LinkedBlockingDeque<>(2);
        //BlockingQueue<String> queue = new ArrayBlockingQueue<String>(2);
        // LinkedBlockingDeque 默认大小为Integer.MAX_VALUE
        for (int i = 0; i < 5; i++) {
            new Thread(new Producer(queue), "Producer"+i).start();
            new Thread(new consumer(queue), "Consumer"+i).start();
        }
    }
}
  • 结果

I have produced:Producer0
消费了:a product-Producer0
I have produced:Producer1
消费了:a product-Producer1
I have produced:Producer2
消费了:a product-Producer2
I have produced:Producer3
I have produced:Producer4
消费了:a product-Producer3
消费了:a product-Producer4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值