Queue 阻塞队列 ArrayBlockingQueue

BlockingQueue 是java.util.concurrent包 下的接口。
阻塞队列:当队列满时,入队线程会被阻塞;当队列为空时,出队线程会被阻塞. put / take

参考:https://www.cnblogs.com/lemon-flm/p/7877898.html

ArrayBlockingQueue在构造时需要指定容量, 并可以选择是否需要公平性,如果公平参数被设置true,等待时间最长的线程会优先得到处理(其实就是通过将ReentrantLock的fair设置为true来 达到这种公平性的:即等待时间最长的线程会先操作)。
通常,公平性会使你在性能上付出代价,只有在的确非常需要的时候再使用它。它是基于数组的阻塞循环队列,此队列按 FIFO(先进先出)原则对元素进行排序。
package com.dh.test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class LearnArrayBlockingQueue {// ArrayBlockingQueue 利用的ReentrantLock的Condition中的方法:await()释放锁,阻塞当前线程; single()唤醒线程
    public static void main(String[] args) throws InterruptedException {
        //ArrayBlockingQueue队列是通过数组来实现的,所以new 该队列时,需要指定初始容量大小。
        BlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(2);
        arrayBlockingQueue.offer("aaaa");
        arrayBlockingQueue.offer("bbbb");
        // 会抛异常 Queue full
        // arrayBlockingQueue.add("dddd");
        // 不会抛异常,返回false
        arrayBlockingQueue.offer("cccc");

        //在添加元素时,ArrayBlockingQueue使用了ReentrantLock用来保证线程安全使用了ReentrantLock用来保证线程安全。
        //默认情况下,ArrayBlockingQueue的构造方法默认fair为false,
        arrayBlockingQueue.take();
        arrayBlockingQueue.take();
        //此时队列为空,出队线程会被阻塞  notEmpty.await()
        Thread thread = new Thread(new MyThread(arrayBlockingQueue));
        thread.start();
        //take会一直阻塞,直到线程给队列放值
        System.out.println(arrayBlockingQueue.take());
    }


}

class MyThread implements Runnable {
    BlockingQueue<String> arrayBlockingQueue;

    public MyThread(BlockingQueue<String> arrayBlockingQueue) {
        this.arrayBlockingQueue = arrayBlockingQueue;
    }

    @Override
    public void run() {
        System.out.println("给队列放值,让队列不为空");
        arrayBlockingQueue.offer("eeee");
    }
}
原文地址:https://www.cnblogs.com/han6/p/11274605.html