Java教程-Java ConcurrentLinkedQueue 类

Java ConcurrentLinkedQueue 类
ConcurrentLinkedQueue 是一个无界线程安全的队列,它按照先进先出(FIFO)的顺序排列元素。新元素会被添加到队列的尾部,而元素从队列的头部被添加。
ConcurrentLinkedQueue 类及其迭代器实现了 Queue 和 Iterator 接口的所有可选方法。
方法
方法名 | 描述 |
---|---|
add() | 在队列的尾部插入指定的元素。 |
addAll() | 将指定集合中存在的所有元素插入到队列的尾部。 |
contains() | 如果队列包含指定的元素,则返回 true。 |
forEach() | 对每个元素执行给定的操作,直到处理完所有元素。 |
isEmpty() | 如果队列不包含任何元素,则返回 true。 |
iterator() | 返回此队列中的元素的迭代器。 |
offer() | 在队列的尾部插入指定的元素。 |
remove() | 从队列中删除指定的元素(如果存在)。 |
removeAll() | 删除队列中存在于指定集合中的所有元素。 |
removeIf() | 删除队列中满足给定谓词过滤器的所有元素。 |
retainAll() | 仅保留队列中存在于指定集合中的元素。 |
size() | 返回队列中的元素数量。 |
spliterator() | 返回此队列中的元素的分割迭代器。 |
toArray() | 返回包含队列中所有元素的数组,元素顺序正确。 |
示例 1
import java.util.concurrent.ConcurrentLinkedQueue;
public class JavaConcurrentLinkedQueueExample1 {
public static void main(String[] args) {
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
for (int i = 1; i <= 5; i++) {
// 在队列的尾部添加元素
queue.add(i);
}
// 在队列的尾部插入指定的元素
queue.offer(6);
System.out.println("Queue: " + queue);
// 如果队列包含指定的元素,则返回 true
if (queue.contains(4)) {
System.out.println("This queue contains 4");
} else {
System.out.println("4 is absent");
}
// 如果队列为空,则返回 true
if (queue.isEmpty()) {
System.out.println("Add some elements because the queue is empty.");
} else {
System.out.println("Queue is not empty");
}
}
}
输出:
Queue: [1, 2, 3, 4, 5, 6]
This queue contains 4
Queue is not empty
示例 2
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
public class JavaConcurrentLinkedQueueExample2 {
public static void main(String[] args) {
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
List<Integer> list = new ArrayList<Integer>();
queue.add(11);
queue.add(100);
queue.add(122);
queue.add(102);
queue.add(112);
list.add(11);
list.add(100);
System.out.println("Elements in queue: " + queue);
// remove() 方法将从队列中删除指定的元素
queue.remove(122);
queue.remove(102);
System.out.println("Remaining elements in queue: " + queue);
// 删除队列中存在于列表中的所有元素
queue.removeAll(list);
System.out.println("Elements of the list will get removed: " + queue);
// 仅保留队列中存在于列表中的元素
queue.retainAll(list);
System.out.println("Queue will retain the elements of the list: " + queue);
}
}
输出:
Elements in queue: [11, 100, 122, 102, 112]
Remaining elements in queue: [11, 100, 112]
Elements of the list will get removed: [112]
Queue will retain the elements of the list: []