ArrayBlockingQueue源码分析及使用

BlockingQueue介绍与常用方法

BlockingQueue是一个阻塞队列。在高并发场景是用得非常多的,在线程池中。如果运行线程数目大于核心线程数目时,也会尝试把新加入的线程放到一个BlockingQueue中去。队列的特性就是先进先出很容易理解,在java里头它的实现类主要有下图的几种,其中最常用到的是ArrayBlockingQueue、LinkedBlockingQueue及SynchronousQueue这三种。


它主要的方法有


BlockingQueue的核心方法:
1、放入数据

  (1) add(object)

    队列没满的话,放入成功。否则抛出异常。

 (2)offer(object):

    表示如果可能的话,将object加到BlockingQueue里,即如果BlockingQueue可以容纳,则返回true,否则返回false.(本方法不阻塞当前执行方法的线程)
 (3)offer(E o, long timeout, TimeUnit unit)

      可以设定等待的时间,如果在指定的时间内,还不能往队列中加入BlockingQueue,则返回失败。
(4)put(object)

       把object加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程阻塞。直到BlockingQueue里面有空间再继续.
2、获取数据
(1)poll(time)

   取走BlockingQueue里排在首位的对象,若不能立即取出,则可以等time参数规定的时间,取不到时返回null;
(2)poll(long timeout, TimeUnit unit)

   从BlockingQueue取出一个队首的对象,如果在指定时间内,队列一旦有数据可取,则立即返回队列中的数据。否则知道时间超时还没有数据可取,返回失败。

(3)take()

  取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到BlockingQueue有新的数据被加入; 
(4)drainTo()

   一次性从BlockingQueue获取所有可用的数据对象(还可以指定获取数据的个数),通过该方法,可以提升获取数据效率;不需要多次分批加锁或释放锁。

ArrayBlockingQueue


一个由数组支持的有界阻塞队列。它的本质是一个基于数组的BlockingQueue的实现。
 它的容纳大小是固定的。此队列按 FIFO(先进先出)原则对元素进行排序。
 队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素。
 新元素插入到队列的尾部,队列检索操作则是从队列头部开始获得元素。 
 这是一个典型的“有界缓存区”,固定大小的数组在其中保持生产者插入的元素和使用者提取的元素。
 一旦创建了这样的缓存区,就不能再增加其容量。
 试图向已满队列中放入元素会导致放入操作受阻塞,直到BlockingQueue里有新的
空间才会被醒继续操作

 试图从空队列中检索元素将导致类似阻塞,直到BlocingkQueue进了新货才会被唤醒。 
 此类支持对等待的生产者线程和使用者线程进行排序的可选公平策略。
 默认情况下,不保证是这种排序。然而,通过在构造函数将公平性 (fairness) 设置为 true 而构造的队列允许按照 FIFO 顺序访问线程。
 公平性通常会降低吞吐量,但也减少了可变性和避免了“不平衡性”。 
 此类及其迭代器实现了 Collection 和 Iterator 接口的所有可选 方法。
 注意1:它是有界阻塞队列。它是数组实现的,是一个典型的“有界缓存区”。数组大小在构造函数指定,而且从此以后不可改变。
 注意2:是它线程安全的,是阻塞的,具体参考BlockingQueue的“注意4”。
 注意3:不接受 null 元素
 注意4:公平性 (fairness)可以在构造函数中指定。

Public Constructors
  ArrayBlockingQueue(int capacity)
Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy.
  ArrayBlockingQueue(int capacity, boolean fair)
Creates an ArrayBlockingQueue with the given (fixed) capacity and the specified access policy.
  ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c)
Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified access policy and initially containing the elements of the given collection, added in traversal order of the collection's iterator.
 如果为true,则按照 FIFO 顺序访问插入或移除时受阻塞线程的队列;如果为 false,则访问顺序是不确定的。
  注意5:它实现了BlockingQueue接口。
  注意6:此类及其迭代器实现了 Collection 和 Iterator 接口的所有可选 方法。
  注意7:其容量在构造函数中指定。容量不可以自动扩展,也没提供手动扩展的接口。

  注意8:在JDK5/6中,LinkedBlockingQueue和ArrayBlocingQueue等对象的poll(long timeout, TimeUnit unit)存在内存泄露
   Leak的对象是AbstractQueuedSynchronizer.Node,
   据称JDK5会在Update12里Fix,JDK6会在Update2里Fix。
源码分析:

    一个基本数组的阻塞队列。可以设置列队的大小。

它的基本原理实际还是数组,只不过存、取、删时都要做队列是否满或空的判断。然后加锁访问。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package java.util.concurrent;  
  2. import java.util.concurrent.locks.Condition;  
  3. import java.util.concurrent.locks.ReentrantLock;  
  4. import java.util.AbstractQueue;  
  5. import java.util.Collection;  
  6. import java.util.Iterator;  
  7. import java.util.NoSuchElementException;  
  8. import java.lang.ref.WeakReference;  
  9. import java.util.Spliterators;  
  10. import java.util.Spliterator;  
  11.   
  12.   
  13. public class ArrayBlockingQueue<E> extends AbstractQueue<E>  
  14.         implements BlockingQueue<E>, java.io.Serializable {  
  15.   
  16.     private static final long serialVersionUID = -817911632652898426L;  
  17.   
  18.     /** 真正存入数据的数组*/  
  19.     final Object[] items;  
  20.   
  21.     /** take, poll, peek or remove的下一个索引 */  
  22.     int takeIndex;  
  23.   
  24.     /** put, offer, or add的下一个索引 */  
  25.     int putIndex;  
  26.   
  27.     /**队列中元素个数*/  
  28.     int count;  
  29.   
  30.   
  31.     /**可重入锁 */  
  32.     final ReentrantLock lock;  
  33.   
  34.     /** 队列不为空的条件 */  
  35.     private final Condition notEmpty;  
  36.   
  37.     /** 队列未满的条件 */  
  38.     private final Condition notFull;  
  39.   
  40.     transient Itrs itrs = null;  
  41.   
  42.   
  43.     /** 
  44.      *当前元素个数-1 
  45.      */  
  46.     final int dec(int i) {  
  47.         return ((i == 0) ? items.length : i) - 1;  
  48.     }  
  49.   
  50.     /** 
  51.      * 返回对应索引上的元素 
  52.      */  
  53.     @SuppressWarnings("unchecked")  
  54.     final E itemAt(int i) {  
  55.         return (E) items[i];  
  56.     }  
  57.   
  58.     /** 
  59.      * 非空检查 
  60.      * 
  61.      * @param v the element 
  62.      */  
  63.     private static void checkNotNull(Object v) {  
  64.         if (v == null)  
  65.             throw new NullPointerException();  
  66.     }  
  67.   
  68.     /** 
  69.      * 元素放入队列,注意调用这个方法时都要先加锁 
  70.      *  
  71.      */  
  72.     private void enqueue(E x) {  
  73.         final Object[] items = this.items;  
  74.         items[putIndex] = x;  
  75.         if (++putIndex == items.length)  
  76.             putIndex = 0;  
  77.         count++;//当前拥有元素个数加1  
  78.         notEmpty.signal();//有一个元素加入成功,那肯定队列不为空  
  79.     }  
  80.   
  81.     /** 
  82.      * 元素出队,注意调用这个方法时都要先加锁 
  83.      *  
  84.      */  
  85.     private E dequeue() {  
  86.         final Object[] items = this.items;  
  87.         @SuppressWarnings("unchecked")  
  88.         E x = (E) items[takeIndex];  
  89.         items[takeIndex] = null;  
  90.         if (++takeIndex == items.length)  
  91.             takeIndex = 0;  
  92.         count--;/当前拥有元素个数减1  
  93.         if (itrs != null)  
  94.             itrs.elementDequeued();  
  95.         notFull.signal();//有一个元素取出成功,那肯定队列不满  
  96.         return x;  
  97.     }  
  98.   
  99.     /** 
  100.      * 指定删除索引上的元素 
  101.      *  
  102.      */  
  103.     void removeAt(final int removeIndex) {  
  104.         final Object[] items = this.items;  
  105.         if (removeIndex == takeIndex) {  
  106.             items[takeIndex] = null;  
  107.             if (++takeIndex == items.length)  
  108.                 takeIndex = 0;  
  109.             count--;  
  110.             if (itrs != null)  
  111.                 itrs.elementDequeued();  
  112.         } else {  
  113.             final int putIndex = this.putIndex;  
  114.             for (int i = removeIndex;;) {  
  115.                 int next = i + 1;  
  116.                 if (next == items.length)  
  117.                     next = 0;  
  118.                 if (next != putIndex) {  
  119.                     items[i] = items[next];  
  120.                     i = next;  
  121.                 } else {  
  122.                     items[i] = null;  
  123.                     this.putIndex = i;  
  124.                     break;  
  125.                 }  
  126.             }  
  127.             count--;  
  128.             if (itrs != null)  
  129.                 itrs.removedAt(removeIndex);  
  130.         }  
  131.         notFull.signal();//有一个元素删除成功,那肯定队列不满  
  132.     }  
  133.   
  134.     /** 
  135.      *  
  136.      * 构造函数,设置队列的初始容量 
  137.      */  
  138.     public ArrayBlockingQueue(int capacity) {  
  139.         this(capacity, false);  
  140.     }  
  141.   
  142.     /** 
  143.      * 构造函数。capacity设置数组大小 ,fair设置是否为公平锁 
  144.      * capacity and the specified access policy. 
  145.      */  
  146.     public ArrayBlockingQueue(int capacity, boolean fair) {  
  147.         if (capacity <= 0)  
  148.             throw new IllegalArgumentException();  
  149.         this.items = new Object[capacity];  
  150.         lock = new ReentrantLock(fair);//是否为公平锁,如果是的话,那么先到的线程先获得锁对象。  
  151.         //否则,由操作系统调度由哪个线程获得锁,一般为false,性能会比较高  
  152.         notEmpty = lock.newCondition();  
  153.         notFull =  lock.newCondition();  
  154.     }  
  155.   
  156.     /** 
  157.      *构造函数,带有初始内容的队列 
  158.      */  
  159.     public ArrayBlockingQueue(int capacity, boolean fair,  
  160.                               Collection<? extends E> c) {  
  161.         this(capacity, fair);  
  162.   
  163.         final ReentrantLock lock = this.lock;  
  164.         lock.lock(); //要给数组设置内容,先上锁  
  165.         try {  
  166.             int i = 0;  
  167.             try {  
  168.                 for (E e : c) {  
  169.                     checkNotNull(e);  
  170.                     items[i++] = e;//依次拷贝内容  
  171.                 }  
  172.             } catch (ArrayIndexOutOfBoundsException ex) {  
  173.                 throw new IllegalArgumentException();  
  174.             }  
  175.             count = i;  
  176.             putIndex = (i == capacity) ? 0 : i;//如果putIndex大于数组大小 ,那么从0重新开始  
  177.         } finally {  
  178.             lock.unlock();//最后一定要释放锁  
  179.         }  
  180.     }  
  181.   
  182.     /** 
  183.      * 添加一个元素,其实super.add里面调用了offer方法 
  184.      */  
  185.     public boolean add(E e) {  
  186.         return super.add(e);  
  187.     }  
  188.   
  189.     /** 
  190.      *加入成功返回true,否则返回false 
  191.      *  
  192.      */  
  193.     public boolean offer(E e) {  
  194.         checkNotNull(e);  
  195.         final ReentrantLock lock = this.lock;  
  196.         lock.lock();//上锁  
  197.         try {  
  198.             if (count == items.length) //超过数组的容量  
  199.                 return false;  
  200.             else {  
  201.                 enqueue(e); //放入元素  
  202.                 return true;  
  203.             }  
  204.         } finally {  
  205.             lock.unlock();  
  206.         }  
  207.     }  
  208.   
  209.     /** 
  210.      * 如果队列已满的话,就会等待 
  211.      */  
  212.     public void put(E e) throws InterruptedException {  
  213.         checkNotNull(e);  
  214.         final ReentrantLock lock = this.lock;  
  215.         lock.lockInterruptibly();//和lock()方法的区别是让它在阻塞时也可抛出异常跳出  
  216.         try {  
  217.             while (count == items.length)  
  218.                 notFull.await(); //这里就是阻塞了,要注意。如果运行到这里,那么它会释放上面的锁,一直等到notify  
  219.             enqueue(e);  
  220.         } finally {  
  221.             lock.unlock();  
  222.         }  
  223.     }  
  224.   
  225.     /** 
  226.      * 带有超时时间的插入方法,unit表示是按秒、分、时哪一种 
  227.      */  
  228.     public boolean offer(E e, long timeout, TimeUnit unit)  
  229.         throws InterruptedException {  
  230.   
  231.         checkNotNull(e);  
  232.         long nanos = unit.toNanos(timeout);  
  233.         final ReentrantLock lock = this.lock;  
  234.         lock.lockInterruptibly();  
  235.         try {  
  236.             while (count == items.length) {  
  237.                 if (nanos <= 0)  
  238.                     return false;  
  239.                 nanos = notFull.awaitNanos(nanos);//带有超时等待的阻塞方法  
  240.             }  
  241.             enqueue(e);//入队  
  242.             return true;  
  243.         } finally {  
  244.             lock.unlock();  
  245.         }  
  246.     }  
  247.   
  248.     //实现的方法,如果当前队列为空,返回null  
  249.     public E poll() {  
  250.         final ReentrantLock lock = this.lock;  
  251.         lock.lock();  
  252.         try {  
  253.             return (count == 0) ? null : dequeue();  
  254.         } finally {  
  255.             lock.unlock();  
  256.         }  
  257.     }  
  258.      //实现的方法,如果当前队列为空,一直阻塞  
  259.     public E take() throws InterruptedException {  
  260.         final ReentrantLock lock = this.lock;  
  261.         lock.lockInterruptibly();  
  262.         try {  
  263.             while (count == 0)  
  264.                 notEmpty.await();//队列为空,阻塞方法  
  265.             return dequeue();  
  266.         } finally {  
  267.             lock.unlock();  
  268.         }  
  269.     }  
  270.     //带有超时时间的取元素方法,否则返回Null  
  271.     public E poll(long timeout, TimeUnit unit) throws InterruptedException {  
  272.         long nanos = unit.toNanos(timeout);  
  273.         final ReentrantLock lock = this.lock;  
  274.         lock.lockInterruptibly();  
  275.         try {  
  276.             while (count == 0) {  
  277.                 if (nanos <= 0)  
  278.                     return null;  
  279.                 nanos = notEmpty.awaitNanos(nanos);//超时等待  
  280.             }  
  281.             return dequeue();//取得元素  
  282.         } finally {  
  283.             lock.unlock();  
  284.         }  
  285.     }  
  286.     //只是看一个队列最前面的元素,取出是不删除队列中的原来元素。队列为空时返回null  
  287.     public E peek() {  
  288.         final ReentrantLock lock = this.lock;  
  289.         lock.lock();  
  290.         try {  
  291.             return itemAt(takeIndex); // 队列为空时返回null  
  292.         } finally {  
  293.             lock.unlock();  
  294.         }  
  295.     }  
  296.   
  297.     /** 
  298.      * 返回队列当前元素个数 
  299.      * 
  300.      */  
  301.     public int size() {  
  302.         final ReentrantLock lock = this.lock;  
  303.         lock.lock();  
  304.         try {  
  305.             return count;  
  306.         } finally {  
  307.             lock.unlock();  
  308.         }  
  309.     }  
  310.   
  311.     /** 
  312.      * 返回当前队列再放入多少个元素就满队 
  313.      */  
  314.     public int remainingCapacity() {  
  315.         final ReentrantLock lock = this.lock;  
  316.         lock.lock();  
  317.         try {  
  318.             return items.length - count;  
  319.         } finally {  
  320.             lock.unlock();  
  321.         }  
  322.     }  
  323.   
  324.     /** 
  325.      *  从队列中删除一个元素的方法。删除成功返回true,否则返回false 
  326.      */  
  327.     public boolean remove(Object o) {  
  328.         if (o == nullreturn false;  
  329.         final Object[] items = this.items;  
  330.         final ReentrantLock lock = this.lock;  
  331.         lock.lock();  
  332.         try {  
  333.             if (count > 0) {  
  334.                 final int putIndex = this.putIndex;  
  335.                 int i = takeIndex;  
  336.                 do {  
  337.                     if (o.equals(items[i])) {  
  338.                         removeAt(i); //真正删除的方法  
  339.                         return true;  
  340.                     }  
  341.                     if (++i == items.length)  
  342.                         i = 0;  
  343.                 } while (i != putIndex);//一直不断的循环取出来做判断  
  344.             }  
  345.             return false;  
  346.         } finally {  
  347.             lock.unlock();  
  348.         }  
  349.     }  
  350.   
  351.     /** 
  352.      * 是否包含一个元素 
  353.      */  
  354.     public boolean contains(Object o) {  
  355.         if (o == nullreturn false;  
  356.         final Object[] items = this.items;  
  357.         final ReentrantLock lock = this.lock;  
  358.         lock.lock();  
  359.         try {  
  360.             if (count > 0) {  
  361.                 final int putIndex = this.putIndex;  
  362.                 int i = takeIndex;  
  363.                 do {  
  364.                     if (o.equals(items[i]))  
  365.                         return true;  
  366.                     if (++i == items.length)  
  367.                         i = 0;  
  368.                 } while (i != putIndex);  
  369.             }  
  370.             return false;  
  371.         } finally {  
  372.             lock.unlock();  
  373.         }  
  374.     }  
  375.   
  376.     /** 
  377.      * 清空队列 
  378.      * 
  379.      */  
  380.     public void clear() {  
  381.         final Object[] items = this.items;  
  382.         final ReentrantLock lock = this.lock;  
  383.         lock.lock();  
  384.         try {  
  385.             int k = count;  
  386.             if (k > 0) {  
  387.                 final int putIndex = this.putIndex;  
  388.                 int i = takeIndex;  
  389.                 do {  
  390.                     items[i] = null;  
  391.                     if (++i == items.length)  
  392.                         i = 0;  
  393.                 } while (i != putIndex);  
  394.                 takeIndex = putIndex;  
  395.                 count = 0;  
  396.                 if (itrs != null)  
  397.                     itrs.queueIsEmpty();  
  398.                 for (; k > 0 && lock.hasWaiters(notFull); k--)  
  399.                     notFull.signal();  
  400.             }  
  401.         } finally {  
  402.             lock.unlock();  
  403.         }  
  404.     }  
  405.   
  406.     /** 
  407.      * 取出所有元素到集合 
  408.      */  
  409.     public int drainTo(Collection<? super E> c) {  
  410.         return drainTo(c, Integer.MAX_VALUE);  
  411.     }  
  412.   
  413.     /** 
  414.      * 取出所有元素到集合 
  415.      */  
  416.     public int drainTo(Collection<? super E> c, int maxElements) {  
  417.         checkNotNull(c);  
  418.         if (c == this)  
  419.             throw new IllegalArgumentException();  
  420.         if (maxElements <= 0)  
  421.             return 0;  
  422.         final Object[] items = this.items;  
  423.         final ReentrantLock lock = this.lock;  
  424.         lock.lock();  
  425.         try {  
  426.             int n = Math.min(maxElements, count);  
  427.             int take = takeIndex;  
  428.             int i = 0;  
  429.             try {  
  430.                 while (i < n) {  
  431.                     @SuppressWarnings("unchecked")  
  432.                     E x = (E) items[take];  
  433.                     c.add(x);  
  434.                     items[take] = null;  
  435.                     if (++take == items.length)  
  436.                         take = 0;  
  437.                     i++;  
  438.                 }  
  439.                 return n;  
  440.             } finally {  
  441.                 // Restore invariants even if c.add() threw  
  442.                 if (i > 0) {  
  443.                     count -= i;  
  444.                     takeIndex = take;  
  445.                     if (itrs != null) {  
  446.                         if (count == 0)  
  447.                             itrs.queueIsEmpty();  
  448.                         else if (i > take)  
  449.                             itrs.takeIndexWrapped();  
  450.                     }  
  451.                     for (; i > 0 && lock.hasWaiters(notFull); i--)  
  452.                         notFull.signal();  
  453.                 }  
  454.             }  
  455.         } finally {  
  456.             lock.unlock();  
  457.         }  
  458.     }  
  459.   
  460.   
  461. }  
使用实例:
生产者-消费者模型

    大量的实现 ArrayBlockingQueue已经做掉了,包括判空,线程挂起等操作都封装在 ArrayBlockingQueue中。生产者只需要关心生产,消费者只需要关心消费。而如果不使用ArrayBlockingQueue的话,具体的生产者还需要去通知消费者,还需要关心整个容器是否满了。从这里可以看出 ArrayBlockingQueue是一种比较好的实现方式,高度的内聚。

Producer.java

[java]  view plain  copy
  1.  
  2. public class Producer implements Runnable{  
  3.       
  4.     //容器  
  5.     private final ArrayBlockingQueue<Bread> queue;  
  6.       
  7.     public Producer(ArrayBlockingQueue<Bread> queue){  
  8.         this.queue = queue;  
  9.     }  
  10.   
  11.     /* (non-Javadoc) 
  12.      * @see java.lang.Runnable#run() 
  13.      */  
  14.     @Override  
  15.     public void run() {  
  16.         while(true){  
  17.             produce();  
  18.         }  
  19.     }  
  20.       
  21.     public void produce(){  
  22.         /** 
  23.          * put()方法是如果容器满了的话就会把当前线程挂起 
  24.          * offer()方法是容器如果满的话就会返回false。 
  25.          */  
  26.         try {  
  27.             Bread bread = new Bread();  
  28.             queue.put(bread);  
  29.             System.out.println("Producer:"+bread);  
  30.         } catch (InterruptedException e) {  
  31.             e.printStackTrace();  
  32.         }  
  33.     }  
  34. }  

Consumer.java

[java]  view plain  copy

  1. public class Consumer implements Runnable{  
  2.       
  3.     //容器  
  4.     private final ArrayBlockingQueue<Bread> queue;  
  5.       
  6.     public Consumer(ArrayBlockingQueue<Bread> queue){  
  7.         this.queue = queue;  
  8.     }  
  9.   
  10.     /* (non-Javadoc) 
  11.      * @see java.lang.Runnable#run() 
  12.      */  
  13.     @Override  
  14.     public void run() {  
  15.         while(true){  
  16.             consume();  
  17.         }  
  18.     }  
  19.       
  20.     public void consume(){  
  21.         /** 
  22.          * take()方法和put()方法是对应的,从中拿一个数据,如果拿不到线程挂起 
  23.          * poll()方法和offer()方法是对应的,从中拿一个数据,如果没有直接返回null 
  24.          */  
  25.         try {  
  26.             Bread bread = queue.take();  
  27.             System.out.println("consumer:"+bread);  
  28.         } catch (InterruptedException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.     }  
  32. }  

Client.java

[java] view plain copy

  1. public class Client {  
  2.   
  3.     /** 
  4.      * @param args 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         int capacity = 10;  
  8.         ArrayBlockingQueue<Bread> queue = new ArrayBlockingQueue<Bread>(capacity);  
  9.   
  10.         new Thread(new Producer(queue)).start();  
  11.         new Thread(new Producer(queue)).start();  
  12.         new Thread(new Consumer(queue)).start();  
  13.         new Thread(new Consumer(queue)).start();  
  14.         new Thread(new Consumer(queue)).start();  
  15.     }  
  16.   
  17. }  


参考:http://blog.csdn.net/evankaka/article/details/51706109
http://blog.csdn.net/hudashi/article/details/7076745


  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,可以为您提供一个简单的Java ArrayBlockingQueue使用例子: ``` import java.util.concurrent.ArrayBlockingQueue; public class ArrayBlockingQueueExample { public static void main(String[] args) { // 创建一个容量为3的数组阻塞队列 ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3); // 添加元素到队列 queue.add("Java"); queue.offer("Python"); try { // 尝试添加一个元素,但队列已满,因此将会被阻塞 queue.put("C++"); } catch (InterruptedException e) { e.printStackTrace(); } // 队列已满,再次添加元素将会抛出异常 try { queue.add("Ruby"); } catch (IllegalStateException e) { System.out.println("队列已满!"); } // 从队列中获取并移除头部元素 System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); // 队列中已没有元素,再次获取元素将返回null System.out.println(queue.poll()); } } ``` 这个例子创建了一个容量为3的ArrayBlockingQueue对象,首先添加了两个元素 Java 和 Python。然后尝试向队列中添加一个元素 C++,但这个队列已满,因此该方法将会被阻塞,直到队列中有空间可用。 接着尝试再次添加一个元素 Ruby,但由于队列已满,该操作将会抛出IllegalStateException异常。 最后,我们从队列中获取并移除了头部的三个元素,然后再次尝试获取一个元素,但由于队列已空,该操作将返回null。 希望这个例子对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值