ArrayBlockingQueue 是一个有界的阻塞队列,它存储由数组在内部支持的元素。
null
- ArrayBlockingQueue 类是Java集合框架的成员。
- 有界意味着它将有一个固定的大小,你知道吗 不能 存储的元素数大于队列的容量。
- 队列还遵循FIFO(先进先出)规则来存储和删除队列中的元素。
- 如果您试图将一个元素放入一个完整的队列,或者从一个空队列中获取一个元素,那么该队列将阻止您。
这个 加(E) 方法插入作为参数传递给 尾 排队的人。如果添加元素超出了队列的容量,那么该方法将抛出非法状态异常。如果元素添加成功,此方法将返回true,否则将抛出IllegalStateException。 语法:
public boolean add(E e)
参数: e–要添加到队列中的元素。 返回值: 如果添加成功,则为true。 抛出: IllegalStateException–如果此队列已满 NullPointerException–如果指定的元素为null
例1 下面的程序演示了如何向ArrayBlockingQueue添加元素。
// Java Program to Demonstrate add(E e) method // of ArrayBlockingQueue. import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; public class GFG { public static void main(String[] args) { // define capacity of ArrayBlockingQueue int capacity = 10 ; // create object of ArrayBlockingQueue ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity); // Add element to ArrayBlockingQueue queue.add( 23 ); // print queue after add operation System.out.println( "After adding 23" ); System.out.println(queue); // add more numbers queue.add( 32 ); queue.add( 45 ); queue.add( 12 ); // print queue after add operation System.out.println( "After adding 32, 45, 12" ); System.out.println(queue); // add more numbers queue.add( 27 ); queue.add( 67 ); // print queue after add operation System.out.println( "After adding 27, 67" ); System.out.println(queue); } } |
Output : After adding 23 [23] After adding 32, 45, 12 [23, 32, 45, 12] After adding 27, 67 [23, 32, 45, 12, 27, 67]
例2 下面的程序演示了如何向ArrayBlockingQueue添加元素,以及在队列已满时引发异常。
// Java Program to Demonstrate add(E e) method // of ArrayBlockingQueue. import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; public class GFG { public static void main(String[] args) { // define capacity of ArrayBlockingQueue to 5 elements int capacity = 5 ; // create object of ArrayBlockingQueue ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity); // Add 5 element to ArrayBlockingQueue queue.add( 23 ); queue.add( 32 ); queue.add( 45 ); queue.add( 12 ); queue.add( 27 ); // print queue after add operation System.out.println( "After adding all 5 elements to queue" ); System.out.println(queue); // check whether queue is full or not. if (queue.remainingCapacity() == 0 ) { System.out.println( "Queue is full" ); } else { System.out.println( "Queue is not full" ); } // try to add more elements // If exception thrown print the exception. try { Boolean response = queue.add( 27 ); } catch (Exception e) { e.printStackTrace(); } } } |
Output : After adding all 5 elements to queue [23, 32, 45, 12, 27] Queue is full java.lang.IllegalStateException: Queue full at java.util.AbstractQueue.add(Unknown Source) at java.util.concurrent.ArrayBlockingQueue.add(Unknown Source) at defaultpackage.GFG.main(GFG.java:38)
参考: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html#add(E)
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END