PriorityBlockingQueue Class in Java

Java 8Object Oriented ProgrammingProgramming

The PriorityBlockingQueue Class in Java has a blocking queue that has unbounded functionality and is based on the class PriorityQueue with the same ordering rules. The PriorityBlockingQueue Class is a part of the Java Collection Framework.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.concurrent.PriorityBlockingQueue;
public class Demo {
   public static void main(String[] args) {
      PriorityBlockingQueue<String> pbQueue = new PriorityBlockingQueue<String>();
      pbQueue.add("James");
      pbQueue.add("May");
      pbQueue.add("John");
      pbQueue.add("Sara");
      pbQueue.add("Anne");
      System.out.println("The elements in PriorityBlockingQueue are: " + pbQueue);
   }
}

The output of the above program is as follows −

Output

The elements in PriorityBlockingQueue are: [Anne, James, John, Sara, May]

Now let us understand the above program.

The PriorityBlockingQueue is created and then elements are added to it. Finally, the elements are displayed in order. A code snippet that demonstrates this is given as follows −

PriorityBlockingQueue<String> pbQueue = new PriorityBlockingQueue<String>();
pbQueue.add("James");
pbQueue.add("May");
pbQueue.add("John");
pbQueue.add("Sara");
pbQueue.add("Anne");
System.out.println("The elements in PriorityBlockingQueue are: " + pbQueue);
raja
Published on 28-Feb-2019 07:34:35
Advertisements