Java并发编程:阻塞队列

本文介绍了Java并发编程中的重要数据结构BlockingQueue,它提供了线程安全的队列访问,常用于生产者-消费者模式。文章详细讨论了ArrayBlockingQueue、LinkedBlockingQueue、DelayQueue、PriorityBlockingQueue和SynchronousQueue等实现类的特点和使用场景,强调了BlockingQueue在多线程环境中的优势和避免使用null的重要性。
摘要由CSDN通过智能技术生成

1. BlockingQueue概述

  • BlockingQueue 是 java.util.concurrent 包下重要的数据结构,区别于普通的队列,BlockingQueue 提供了线程安全的队列访问方式,并发包下很多高级同步类的实现都是基于 BlockingQueue 实现的。BlockingQueue 一般用于生产者-消费者模式,生产者是往队列里添加元素的线程,消费者是从队列里拿元素的线程。BlockingQueue 就是存放元素的容器。
    queue
  • 阻塞队列:必须要阻塞 / 不得不阻塞
  • 试图从空的队列中获取元素的线程将会被阻塞,直到其他线程往空的队列中插入新的元素。
  • 试图往满的队列中添加元素的线程将会被阻塞,直到其他线程从队列中移除一个或多个元素或者完全清空队列。
  • 在多线程领域,所谓阻塞,在某些情况下会挂起线程,一旦条件满足,被挂起的线程又会自动被唤醒。
  • 为什么需要 BlockingQueue 呢?好处是我们不需要关心什么时候需要阻塞线程,什么时候需要唤醒线程,因为这一切 BlockingQueue 都解决了。

  • 不能往阻塞队列中插入 null,会抛出空指针异常。
  • 可以访问阻塞队列中的任意元素,调用 remove(o) 可以将队列之中的特定对象移除,但并不高效,尽量避免使用。
package com.java.blockingqueue;

import org.junit.Test;

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

/**
 * @author rrqstart
 * @Description 阻塞队列 BlockingQueue
 */
public class BlockingQueueTest {
   
    @Test
    public void test1() {
   
    	//new ArrayBlockingQueue<>(2)等价于new ArrayBlockingQueue<>(2,false)
    	//即不保证线程公平的访问队列。公平性与否使用可重入锁实现。
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(2); //new Object[2];

        //public abstract boolean add(@NotNull E e)
        System.out.println(blockingQueue.add("a")); //true
        System.out.println(blockingQueue.add("b")); //true
//        System.out.println(blockingQueue.add("x")); //java.lang.IllegalStateException: Queue full

        //public abstract E remove()
        //Retrieves and removes the head of this queue. This method differs from poll only in that it throws an exception if this queue is empty.
        System.out.println(blockingQueue.remove()); //a
        System.out.println(blockingQueue.remove()); //b
//        System.out.println(blockingQueue.remove()); //java.util.NoSuchElementException

        //public abstract int size()
        //Returns the number of elements in this collection. If this collection contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
        System.out.println(blockingQueue.size()); //0

        //public abstract E element():检查但不删除此队列的头
        //Retrieves, but does not remove, the head of this queue. This method differs from pee
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值