The PriorityBlockingQueue class is part of the java.util.concurrent package and implements a thread-safe, priority-based blocking queue. It is similar to the PriorityQueue, but it supports operations for blocking threads, such as take() and put() which are not available in PriorityQueue.
- Thread-safe and supports concurrent access
- Elements are ordered by priority, not insertion order
- Can block threads when the queue is empty or full
- Allows custom prioritization via a comparator or natural ordering
Example: This example demonstrates adding elements to a PriorityBlockingQueue and printing the queue, which displays the elements in their internal order, not necessarily the order they were added.
// Adding elements to priorityBlockingQueue
import java.util.concurrent.PriorityBlockingQueue;
public class Geeks {
public static void main(String[] args) {
// Create a PriorityBlockingQueue
PriorityBlockingQueue<Integer> q
= new PriorityBlockingQueue<>();
// Add elements to the q
q.add(10);
q.add(5);
q.add(20);
q.add(1);
System.out.println("PriorityBlockingQueue: " + q);
}
}
Output
PriorityBlockingQueue: [1, 5, 20, 10]
PriorityBlockingQueue Hierarchy
The below diagram demonstrates the class and interface hierarchy of PriorityBlockingQueue, showing its relationships with Queue, BlockingQueue, AbstractQueue and AbstractCollection.