BlockingQueue and PriorityBlockingQueue are two different implementations of the Queue interface in Java Collections that provide different mechanisms for managing the order and priority of elements in the queue.
BlockingQueue is an interface that extends the Queue interface and provides additional methods for working with a queue that is blocking, meaning that operations such as put and take can block if the queue is full or empty, respectively. BlockingQueue is useful for managing asynchronous tasks where one or more threads may be waiting for tasks to complete before continuing.
PriorityBlockingQueue is a class that implements the BlockingQueue interface and provides a way to manage elements in the queue based on their priority. Elements in a PriorityBlockingQueue are ordered according to their natural ordering or according to a specified Comparator. When an element is added to the queue, it is inserted into the queue in the appropriate position based on its priority.
Here is an example of using BlockingQueue:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ExampleBlockingQueue {
public static void main(String[] args) {
BlockingQueue<String> queue = new LinkedBlockingQueue<>(5);
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 10; i++) {
String message = "Message " + i;
queue.put(message);
System.out.println("Produced: " + message);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread consumer = new Thread(() -> {
try {
while (true) {
String message = queue.take();
System.out.println("Consumed: " + message);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producer.start();
consumer.start();
}
}
In this example, we create a LinkedBlockingQueue with a capacity of 5 elements. We then create a producer thread and a consumer thread. The producer thread adds 10 messages to the queue using the put method, which blocks if the queue is full. The consumer thread uses the take method to remove messages from the queue, which blocks if the queue is empty.
Here is an example of using PriorityBlockingQueue:
import java.util.concurrent.PriorityBlockingQueue;
public class ExamplePriorityBlockingQueue {
public static void main(String[] args) {
PriorityBlockingQueue<String> queue = new PriorityBlockingQueue<>();
queue.add("C");
queue.add("A");
queue.add("B");
System.out.println(queue.take()); // Output: A
System.out.println(queue.take()); // Output: B
System.out.println(queue.take()); // Output: C
}
}
In this example, we create a PriorityBlockingQueue and add three strings to it in an arbitrary order. When we call take on the queue, the element with the highest priority (in this case, "A") is removed from the queue and returned. We then call take twice more to remove the remaining elements from the queue in priority order.