Java中的 ArrayBlockingQueue 类
ArrayBlockingQueue类是一个由数组支持的有界阻塞队列。有界,意味着队列的大小是固定的。一旦创建,容量将无法更改。尝试将元素放入完整队列将导致操作阻塞。同样,从空队列中获取元素的尝试也将被阻止。 ArrayBlockingQueue 的有界性最初可以绕过容量作为 ArrayBlockingQueue 的构造函数中的参数来实现。此队列对元素进行 FIFO(先进先出)排序。这意味着该队列的头部是该队列中存在的元素中最旧的元素。
该队列的尾部是该队列元素中的最新元素。新插入的元素总是插入到队列的尾部,队列检索操作获取队列头部的元素。
此类及其迭代器实现了Collection和Iterator接口的所有可选方法。此类是Java集合框架的成员。
ArrayBlockingQueue 的层次结构
此类扩展 AbstractQueue
宣言
public class ArrayBlockingQueue
这里, E是存储在集合中的元素的类型。
ArrayBlockingQueue 的构造函数
在这里,容量是 数组阻塞队列的大小。
1. ArrayBlockingQueue(int capacity):使用给定(固定)容量和默认访问策略创建一个ArrayBlockingQueue。
ArrayBlockingQueue
2. ArrayBlockingQueue(int capacity, boolean fair):创建具有给定(固定)容量和指定访问策略的ArrayBlockingQueue。如果公允价值为真,则在插入或删除时阻塞的线程的队列访问将按 FIFO 顺序处理;如果为 false,则未指定访问顺序。
ArrayBlockingQueue
3. ArrayBlockingQueue(int capacity, boolean fair, Collection c):创建具有给定(固定)容量、指定访问策略并最初包含给定集合元素的ArrayBlockingQueue,按集合迭代器的遍历顺序添加。如果公允价值为真,则在插入或删除时阻塞的线程的队列访问将按 FIFO 顺序处理;如果为 false,则未指定访问顺序。
ArrayBlockingQueue
例子:
Java
// Java program to demonstrate
// ArrayBlockingQueue(int initialCapacity)
// constructor
import java.util.concurrent.ArrayBlockingQueue;
public class ArrayBlockingQueueDemo {
public static void main(String[] args)
{
// define capacity of ArrayBlockingQueue
int capacity = 15;
// create object of ArrayBlockingQueue
// using ArrayBlockingQueue(int initialCapacity) constructor
ArrayBlockingQueue abq = new ArrayBlockingQueue(capacity);
// add numbers
abq.add(1);
abq.add(2);
abq.add(3);
// print queue
System.out.println("ArrayBlockingQueue:" + abq);
}
}
Java
// Java Program to Demonstrate adding
// elements to an ArrayBlockingQueue.
import java.util.concurrent.ArrayBlockingQueue;
public class AddingElementsExample {
public static void main(String[] args)
{
// define capacity of ArrayBlockingQueue
int capacity = 15;
// create object of ArrayBlockingQueue
ArrayBlockingQueue abq = new ArrayBlockingQueue(capacity);
// add numbers
abq.add(1);
abq.add(2);
abq.add(3);
// print queue
System.out.println("ArrayBlockingQueue:" + abq);
}
}
Java
// Java program to demonstrate removal of
// elements from an AbstractQueue
import java.util.concurrent.ArrayBlockingQueue;
public class RemovingElementsExample {
public static void main(String[] args)
{
// define capacity of ArrayBlockingQueue
int capacity = 15;
// create object of ArrayBlockingQueue
ArrayBlockingQueue abq = new ArrayBlockingQueue(capacity);
// add numbers
abq.add(1);
abq.add(2);
abq.add(3);
// print queue
System.out.println("ArrayBlockingQueue:" + abq);
// remove 223
boolean response = abq.remove(2);
// print Queue
System.out.println("Removal of 2 :" + response);
// print Queue
System.out.println("queue contains " + abq);
// remove all the elements
abq.clear();
// print queue
System.out.println("ArrayBlockingQueue:" + abq);
}
}
Java
// Java program to demonstrate accessing
// elements of ArrayBlockingQueue
import java.util.concurrent.ArrayBlockingQueue;
public class AccessingElementsExample {
public static void main(String[] args)
{
// Define capacity of ArrayBlockingQueue
int capacity = 5;
// Create object of ArrayBlockingQueue
ArrayBlockingQueue queue = new ArrayBlockingQueue(capacity);
// Add element to ArrayBlockingQueue
queue.add(23);
queue.add(32);
queue.add(45);
queue.add(12);
// Print queue after adding numbers
System.out.println("After adding numbers queue is ");
System.out.println(queue);
// Print head of queue using peek() method
System.out.println("Head of queue " + queue.peek());
}
}
Java
// Java Program to Demonstrate iterating
// over ArrayBlockingQueue.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.*;
public class TraversingExample {
public static void main(String[] args)
{
// Define capacity of ArrayBlockingQueue
int capacity = 5;
// Create object of ArrayBlockingQueue
ArrayBlockingQueue queue = new ArrayBlockingQueue(capacity);
// Add 5 elements to ArrayBlockingQueue
queue.offer("User");
queue.offer("Employee");
queue.offer("Manager");
queue.offer("Analyst");
queue.offer("HR");
// Print queue
System.out.println("Queue is " + queue);
// Call iterator() method and Create an iterator
Iterator iteratorValues = queue.iterator();
// Print elements of iterator
System.out.println("\nThe iterator values:");
while (iteratorValues.hasNext()) {
System.out.println(iteratorValues.next());
}
}
}
ArrayBlockingQueue:[1, 2, 3]
基本操作
1.添加元素
add(E e) 方法将作为参数传递给该方法的元素插入到此队列的尾部。如果添加元素超出队列的容量,则该方法将抛出IllegalStateException 。如果添加元素成功,则此方法返回 true,否则将抛出 IllegalStateException。
Java
// Java Program to Demonstrate adding
// elements to an ArrayBlockingQueue.
import java.util.concurrent.ArrayBlockingQueue;
public class AddingElementsExample {
public static void main(String[] args)
{
// define capacity of ArrayBlockingQueue
int capacity = 15;
// create object of ArrayBlockingQueue
ArrayBlockingQueue abq = new ArrayBlockingQueue(capacity);
// add numbers
abq.add(1);
abq.add(2);
abq.add(3);
// print queue
System.out.println("ArrayBlockingQueue:" + abq);
}
}
ArrayBlockingQueue:[1, 2, 3]
2. 移除元素
remove(Object o) 方法从该队列中移除指定元素的单个实例(如果存在)。如果此队列包含一个或多个这样的元素,我们可以说该方法删除了一个元素 e,使得 o.equals(e)。如果此队列包含我们要删除的指定元素,Remove() 方法将返回 true。
Java
// Java program to demonstrate removal of
// elements from an AbstractQueue
import java.util.concurrent.ArrayBlockingQueue;
public class RemovingElementsExample {
public static void main(String[] args)
{
// define capacity of ArrayBlockingQueue
int capacity = 15;
// create object of ArrayBlockingQueue
ArrayBlockingQueue abq = new ArrayBlockingQueue(capacity);
// add numbers
abq.add(1);
abq.add(2);
abq.add(3);
// print queue
System.out.println("ArrayBlockingQueue:" + abq);
// remove 223
boolean response = abq.remove(2);
// print Queue
System.out.println("Removal of 2 :" + response);
// print Queue
System.out.println("queue contains " + abq);
// remove all the elements
abq.clear();
// print queue
System.out.println("ArrayBlockingQueue:" + abq);
}
}
ArrayBlockingQueue:[1, 2, 3]
Removal of 2 :true
queue contains [1, 3]
ArrayBlockingQueue:[]
3. 访问元素
Queue接口提供的 peek() 方法用于返回队列的头部。它检索但不删除此队列的头部。如果队列为空,则此方法返回 null。
Java
// Java program to demonstrate accessing
// elements of ArrayBlockingQueue
import java.util.concurrent.ArrayBlockingQueue;
public class AccessingElementsExample {
public static void main(String[] args)
{
// Define capacity of ArrayBlockingQueue
int capacity = 5;
// Create object of ArrayBlockingQueue
ArrayBlockingQueue queue = new ArrayBlockingQueue(capacity);
// Add element to ArrayBlockingQueue
queue.add(23);
queue.add(32);
queue.add(45);
queue.add(12);
// Print queue after adding numbers
System.out.println("After adding numbers queue is ");
System.out.println(queue);
// Print head of queue using peek() method
System.out.println("Head of queue " + queue.peek());
}
}
After adding numbers queue is
[23, 32, 45, 12]
Head of queue 23
4. 遍历
ArrayBlockingQueue类的 iterator() 方法用于以适当的顺序返回与该队列相同元素的迭代器。此方法返回的元素包含从 first(head) 到 last(tail) 顺序的元素。返回的迭代器是弱一致的。
Java
// Java Program to Demonstrate iterating
// over ArrayBlockingQueue.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.*;
public class TraversingExample {
public static void main(String[] args)
{
// Define capacity of ArrayBlockingQueue
int capacity = 5;
// Create object of ArrayBlockingQueue
ArrayBlockingQueue queue = new ArrayBlockingQueue(capacity);
// Add 5 elements to ArrayBlockingQueue
queue.offer("User");
queue.offer("Employee");
queue.offer("Manager");
queue.offer("Analyst");
queue.offer("HR");
// Print queue
System.out.println("Queue is " + queue);
// Call iterator() method and Create an iterator
Iterator iteratorValues = queue.iterator();
// Print elements of iterator
System.out.println("\nThe iterator values:");
while (iteratorValues.hasNext()) {
System.out.println(iteratorValues.next());
}
}
}
Queue is [User, Employee, Manager, Analyst, HR]
The iterator values:
User
Employee
Manager
Analyst
HR
ArrayBlockingQueue 的方法
这里, E是这个集合中保存的元素的类型 METHOD DESCRIPTIONadd(E e) Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue’s capacity, returning true upon success and throwing an IllegalStateException if this queue is full. clear() Atomically removes all of the elements from this queue. contains(Object o) Returns true if this queue contains the specified element. drainTo(Collection super E> c) Removes all available elements from this queue and adds them to the given collection. drainTo(Collection super E> c, int maxElements) Removes at most the given number of available elements from this queue and adds them to the given collection. forEach(Consumer super E> action) Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. iterator() Returns an iterator over the elements in this queue in the proper sequence. offer(E e) Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue’s capacity, returning true upon success and false if this queue is full. offer(E e, long timeout, TimeUnit unit) Inserts the specified element at the tail of this queue, waiting up to the specified wait time for space to become available if the queue is full. put(E e) Inserts the specified element at the tail of this queue, waiting for space to become available if the queue is full. remainingCapacity() Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking. remove(Object o) Removes a single instance of the specified element from this queue, if it is present. removeAll(Collection> c) Removes all of this collection’s elements that are also contained in the specified collection (optional operation). removeIf(Predicate super E> filter) Removes all of the elements of this collection that satisfy the given predicate. retainAll(Collection> c) Retains only the elements in this collection that are contained in the specified collection (optional operation). size() Returns the number of elements in this queue. spliterator() Returns a Spliterator over the elements in this queue. toArray() Returns an array containing all of the elements in this queue, in proper sequence. toArray(T[] a) Returns an array containing all of the elements in this queue, in proper sequence; the runtime type of the returned array is that of the specified array.
在类Java.util.AbstractQueue 中声明的方法
METHOD | DESCRIPTION |
---|---|
addAll(Collection extends E> c) | Adds all of the elements in the specified collection to this queue. |
element() | Retrieves, but does not remove, the head of this queue. |
remove() | Retrieves and removes the head of this queue. |
在类Java.util.AbstractCollection 中声明的方法
METHOD | DESCRIPTION |
---|---|
containsAll(Collection> c) | Returns true if this collection contains all of the elements in the specified collection. |
isEmpty() | Returns true if this collection contains no elements. |
toString() | Returns a string representation of this collection. |
在接口Java.util.concurrent.BlockingQueue 中声明的方法
METHOD | DESCRIPTION |
---|---|
poll(long timeout, TimeUnit unit) | Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available. |
take() | Retrieves and removes the head of this queue, waiting if necessary until an element becomes available. |
在接口Java.util.Collection 中声明的方法
METHOD | DESCRIPTION |
---|---|
addAll(Collection extends E> c) | Adds all of the elements in the specified collection to this collection (optional operation). |
containsAll(Collection> c) | Returns true if this collection contains all of the elements in the specified collection. |
equals(Object o) | Compares the specified object with this collection for equality. |
hashCode() | Returns the hash code value for this collection. |
isEmpty() | Returns true if this collection contains no elements. |
parallelStream() | Returns a possibly parallel Stream with this collection as its source. |
stream() | Returns a sequential Stream with this collection as its source. |
toArray(IntFunction | Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array. |
在接口Java .util.Queue 中声明的方法
METHOD | DESCRIPTION |
---|---|
element() | Retrieves, but does not remove, the head of this queue. |
peek() | Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. |
poll() | Retrieves and removes the head of this queue, or returns null if this queue is empty. |
remove() | Retrieves and removes the head of this queue. |
结论: ArrayBlockingQueue 通常用于线程安全环境中,您希望阻止两个或多个对单个资源的操作,只允许一个线程。此外,我们可以使用容量边界因子阻塞线程。
参考: Java : Java