Java Program to Implement PriorityBlockingQueue API
Last Updated :
20 Oct, 2022
PriorityBlockingQueue is an unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. The “blocking” part of the name is added to imply the thread will block waiting until there’s an item available on the queue. This class does not permit null elements. A priority queue relying on natural ordering also does not permit the insertion of non-comparable objects (doing so results in ClassCastException).
It implements Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E> interfaces and extends AbstractQueue<E> class.
Declaration:
public class PriorityBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, Serializable
// Here, E is the type of elements held in this collection
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractQueue<E>
java.util.concurrent.PriorityBlockingQueue<E>
Implementation:
Example
Java
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
PriorityBlockingQueue<Integer> priorityBlockingQueue
= new PriorityBlockingQueue<>();
new Thread(() -> {
System.out.println( "Waiting to poll ..." );
try {
while ( true ) {
Integer poll
= priorityBlockingQueue.take();
System.out.println( "Polled : " + poll);
Thread.sleep(
TimeUnit.SECONDS.toMillis( 1 ));
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
Thread.sleep(TimeUnit.SECONDS.toMillis( 2 ));
priorityBlockingQueue.add( 1 );
Thread.sleep(TimeUnit.SECONDS.toMillis( 2 ));
priorityBlockingQueue.add( 2 );
Thread.sleep(TimeUnit.SECONDS.toMillis( 2 ));
priorityBlockingQueue.add( 3 );
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...