Java中的阻塞队列笔记

基类BlockingQueue定义的常用方法如下:

.抛出异常特殊值阻塞超时
插入add(e)offer(e)put(e)offer(e, time, unit)
移除remove()poll()take()poll(time, unit)
检查element()peek()不可用不可用
  1. add(anObject):把anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则抛出异常
  2. offer(anObject):表示如果可能的话,将anObject加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false.
  3. poll(time):取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null
  4. put(anObject):把anObject加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断直到BlockingQueue里面有空间再继续.
  5. take():取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到Blocking有新的对象被加入为止

其中:BlockingQueue 不接受null 元素。试图add、put 或offer 一个null 元素时,某些实现会抛出NullPointerException。null 被用作指示poll 操作失败的警戒值。


JDK7提供了7个阻塞队列

ArrayBlockingQueue :一个由数组结构组成的有界阻塞队列。
LinkedBlockingQueue: 一个由链表结构组成的有界阻塞队列。
PriorityBlockingQueue :一个支持优先级排序的无界阻塞队列。
DelayQueue:一个使用优先级队列实现的无界阻塞队列。 SynchronousQueue:一个不存储元素的阻塞队列。
LinkedTransferQueue:一个由链表结构组成的无界阻塞队列。
LinkedBlockingDeque:一个由链表结构组成的双向阻塞队列。

ArrayBlockingQueue
是一个用数组实现的有界阻塞队列。此队列按照先进先出(FIFO)的原则对元素进行排序。默认情况下不保证访问者公平的访问队列,所谓公平访问队列是指阻塞的所有生产者线程或消费者线程,当队列可用时,可以按照阻塞的先后顺序访问队列,即先阻塞的生产者线程,可以先往队列里插入元素,先阻塞的消费者线程,可以先从队列里获取元素。
  在ArrayBlockingQueue内部,维护了一个定长数组,以便缓存队列中的数据对象,这是一个常用的阻塞队列,除了一个定长数组外,ArrayBlockingQueue内部还保存着两个整形变量,分别标识着队列的头部和尾部在数组中的位置。
  ArrayBlockingQueue在生产者放入数据和消费者获取数据,都是共用同一个锁对象,由此也意味着两者无法真正并行运行,这点尤其不同于LinkedBlockingQueue;按照实现原理来分析,ArrayBlockingQueue完全可以采用分离锁,从而实现生产者和消费者操作的完全并行运行。Doug Lea之所以没这样去做,也许是因为ArrayBlockingQueue的数据写入和获取操作已经足够轻巧,以至于引入独立的锁机制,除了给代码带来额外的复杂性外,其在性能上完全占不到任何便宜。 ArrayBlockingQueue和LinkedBlockingQueue间还有一个明显的不同之处在于,前者在插入或删除元素时不会产生或销毁任何额外的对象实例,而后者则会生成一个额外的Node对象。这在长时间内需要高效并发地处理大批量数据的系统中,其对于GC的影响还是存在一定的区别。
  
LinkedBlockingQueue
是一个用链表实现的有界阻塞队列。此队列的默认和最大长度为Integer.MAX_VALUE。此队列按照先进先出的原则对元素进行排序。
  LinkedBlockingQueue之所以能够高效的处理并发数据,还因为其对于生产者端和消费者端分别采用了独立的锁来控制数据同步,这也意味着在高并发的情况下生产者和消费者可以并行地操作队列中的数据,以此来提高整个队列的并发性能

PriorityBlockingQueue
是一个支持优先级的无界队列。默认情况下元素采取自然顺序排列,也可以通过比较器comparator来指定元素的排序规则。元素按照升序排列。

DelayQueue
是一个支持延时获取元素的无界阻塞队列。队列使用PriorityQueue来实现。队列中的元素必须实现Delayed接口,在创建元素时可以指定多久才能从队列中获取当前元素。只有在延迟期满时才能从队列中提取元素。我们可以将DelayQueue运用在以下应用场景:
缓存系统的设计:可以用DelayQueue保存缓存元素的有效期,使用一个线程循环查询DelayQueue,一旦能从DelayQueue中获取元素时,表示缓存有效期到了。
定时任务调度。使用DelayQueue保存当天将会执行的任务和执行时间,一旦从DelayQueue中获取到任务就开始执行,从比如TimerQueue就是使用DelayQueue实现的。

SynchronousQueue
是一个不存储元素的阻塞队列,类似于无中介的直接交易,有点像原始社会中的生产者和消费者,生产者拿着产品去集市销售给产品的最终消费者,而消费者必须亲自去集市找到所要商品的直接生产者,如果一方没有找到合适的目标,那么对不起,大家都在集市等待。每一个put操作必须等待一个take操作,否则不能继续添加元素。SynchronousQueue可以看成是一个传球手,负责把生产者线程处理的数据直接传递给消费者线程。队列本身并不存储任何元素,非常适合于传递性场景,比如在一个线程中使用的数据,传递给另外一个线程使用,SynchronousQueue的吞吐量高于LinkedBlockingQueue 和 ArrayBlockingQueue。

LinkedTransferQueue
是一个由链表结构组成的无界阻塞TransferQueue队列。相对于其他阻塞队列,LinkedTransferQueue多了tryTransfer和transfer方法。

LinkedBlockingDeque
是一个由链表结构组成的双向阻塞队列。所谓双向队列指的你可以从队列的两端插入和移出元素。双端队列因为多了一个操作队列的入口,在多线程同时入队时,也就减少了一半的竞争。相比其他的阻塞队列,LinkedBlockingDeque多了addFirst,addLast,offerFirst,offerLast,peekFirst,peekLast等方法,以First单词结尾的方法,表示插入,获取(peek)或移除双端队列的第一个元素。以Last单词结尾的方法,表示插入,获取或移除双端队列的最后一个元素。另外插入方法add等同于addLast,移除方法remove等效于removeFirst。但是take方法却等同于takeFirst,不知道是不是Jdk的bug,使用时还是用带有First和Last后缀的方法更清楚。

代码:


class Producer implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        // 声明一个容量为10的缓存队列
//        BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
//        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
        BlockingQueue<String> queue = new SynchronousQueue<>();

        Producer producer1 = new Producer(queue);
        Producer producer2 = new Producer(queue);
        Producer producer3 = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        // 借助Executors
        ExecutorService service = Executors.newCachedThreadPool();
        // 启动线程
        service.execute(producer1);
        service.execute(producer2);
        service.execute(producer3);
        service.execute(consumer);

        // 执行10s
        Thread.sleep(5 * 1000);
        producer1.stop();
        producer2.stop();
        producer3.stop();

        Thread.sleep(2000);
        // 退出Executor
        service.shutdown();
    }

    private volatile boolean isRunning = true;
    private BlockingQueue queue;
    private static AtomicInteger count = new AtomicInteger();
    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;

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

    public void run() {
        String data = null;
        Random r = new Random();

//        System.out.println("启动生产者线程!");
        try {
            while (isRunning) {
//                System.out.println("正在生产数据...");
                Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP));

                data = "data:" + count.incrementAndGet();
                System.out.println(Thread.currentThread().getName()+" 将数据:" + data + "放入队列...");
                if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
                    System.out.println("放入数据失败:" + data);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        } finally {
            System.out.println("退出生产者线程!");
        }
    }

    public void stop() {
        isRunning = false;
    }
}


class Consumer implements Runnable {

    private BlockingQueue<String> queue;
    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;

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

    public void run() {
        System.out.println("启动消费者线程!");
        Random r = new Random();
        boolean isRunning = true;
        try {
            while (isRunning) {
//                System.out.println("正从队列获取数据...");
                String data = queue.poll(2, TimeUnit.SECONDS);
                if (null != data) {
//                    System.out.println("拿到数据:" + data);
                    System.out.println(Thread.currentThread().getName()+" 正在消费数据:" + data);
                    Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP));
                } else {
                    // 超过2s还没数据,认为所有生产线程都已经退出,自动退出消费线程。
                    isRunning = false;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        } finally {
            System.out.println("退出消费者线程!");
        }
    }
}

队列生成结果对比
使用LinkedBlockingQueue ,生成消费22个数据

启动消费者线程!
pool-1-thread-1 将数据:data:1放入队列...
pool-1-thread-4 正在消费数据:data:1
pool-1-thread-3 将数据:data:2放入队列...
pool-1-thread-2 将数据:data:3放入队列...
pool-1-thread-4 正在消费数据:data:2
pool-1-thread-2 将数据:data:4放入队列...
pool-1-thread-1 将数据:data:5放入队列...
pool-1-thread-3 将数据:data:6放入队列...
pool-1-thread-3 将数据:data:7放入队列...
pool-1-thread-1 将数据:data:8放入队列...
pool-1-thread-3 将数据:data:9放入队列...
pool-1-thread-4 正在消费数据:data:3
pool-1-thread-3 将数据:data:10放入队列...
pool-1-thread-3 将数据:data:11放入队列...
pool-1-thread-2 将数据:data:12放入队列...
pool-1-thread-1 将数据:data:13放入队列...
pool-1-thread-4 正在消费数据:data:4
pool-1-thread-1 将数据:data:14放入队列...
pool-1-thread-4 正在消费数据:data:5
pool-1-thread-3 将数据:data:15放入队列...
pool-1-thread-4 正在消费数据:data:6
pool-1-thread-3 将数据:data:16放入队列...
pool-1-thread-2 将数据:data:17放入队列...
pool-1-thread-1 将数据:data:18放入队列...
pool-1-thread-3 将数据:data:19放入队列...
pool-1-thread-4 正在消费数据:data:7
pool-1-thread-2 将数据:data:20放入队列...
pool-1-thread-4 正在消费数据:data:8
pool-1-thread-4 正在消费数据:data:9
pool-1-thread-3 将数据:data:21放入队列...
pool-1-thread-1 将数据:data:22放入队列...
pool-1-thread-4 正在消费数据:data:10
退出生产者线程!
pool-1-thread-4 正在消费数据:data:11
退出生产者线程!
pool-1-thread-4 正在消费数据:data:12
退出生产者线程!
pool-1-thread-4 正在消费数据:data:13
pool-1-thread-4 正在消费数据:data:14
pool-1-thread-4 正在消费数据:data:15
pool-1-thread-4 正在消费数据:data:16
pool-1-thread-4 正在消费数据:data:17
pool-1-thread-4 正在消费数据:data:18
pool-1-thread-4 正在消费数据:data:19
pool-1-thread-4 正在消费数据:data:20
pool-1-thread-4 正在消费数据:data:21
pool-1-thread-4 正在消费数据:data:22
Disconnected from the target VM, address: '127.0.0.1:41242', transport: 'socket'
退出消费者线程!

Process finished with exit code 0

使用SynchronousQueue ,生成消费13个数据,
注意: 因为只能操作一个数据,当并发放入多条数据时,可能会出现插入失败的情况.

启动消费者线程!
pool-1-thread-2 将数据:data:1放入队列...
pool-1-thread-4 正在消费数据:data:1
pool-1-thread-2 将数据:data:2放入队列...
pool-1-thread-3 将数据:data:3放入队列...
pool-1-thread-1 将数据:data:4放入队列...
pool-1-thread-4 正在消费数据:data:4
pool-1-thread-1 将数据:data:5放入队列...
pool-1-thread-4 正在消费数据:data:5
pool-1-thread-4 正在消费数据:data:3
pool-1-thread-1 将数据:data:6放入队列...
放入数据失败:data:2
pool-1-thread-3 将数据:data:7放入队列...
pool-1-thread-4 正在消费数据:data:7
pool-1-thread-2 将数据:data:8放入队列...
pool-1-thread-3 将数据:data:9放入队列...
pool-1-thread-4 正在消费数据:data:9
pool-1-thread-4 正在消费数据:data:8
放入数据失败:data:6
pool-1-thread-3 将数据:data:10放入队列...
pool-1-thread-2 将数据:data:11放入队列...
pool-1-thread-1 将数据:data:12放入队列...
pool-1-thread-4 正在消费数据:data:12
pool-1-thread-1 将数据:data:13放入队列...
pool-1-thread-4 正在消费数据:data:13
退出生产者线程!
pool-1-thread-4 正在消费数据:data:11
退出生产者线程!
放入数据失败:data:10
退出生产者线程!
Disconnected from the target VM, address: '127.0.0.1:44066', transport: 'socket'
退出消费者线程!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值