Skip to content

Commit 77c6b18

Browse files
committed
feat: add PriorityBlockingQueueExample demonstrating priority-based producer-consumer with thread-safe queues
Implemented PriorityBlockingQueueExample.java to illustrate how PriorityBlockingQueue handles concurrent producer-consumer operations using natural ordering. Includes comparisons with LinkedBlockingQueue and SynchronousQueue to highlight differences in blocking, ordering, and concurrency control mechanisms. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 9758a72 commit 77c6b18

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import java.util.Comparator;
2+
import java.util.concurrent.*;
3+
4+
class Producer implements Runnable {
5+
private BlockingQueue<Integer> queue;
6+
private int value = 0;
7+
8+
public Producer(BlockingQueue<Integer> queue) {
9+
this.queue = queue;
10+
}
11+
12+
@Override
13+
public void run() {
14+
while (true) {
15+
try {
16+
System.out.println("Producer produced: " + value);
17+
queue.put(value++);
18+
Thread.sleep(1000);
19+
} catch (Exception e) {
20+
Thread.currentThread().interrupt();
21+
System.out.println("Producer interrupted");
22+
}
23+
}
24+
}
25+
}
26+
27+
class Consumer implements Runnable {
28+
private BlockingQueue<Integer> queue;
29+
30+
public Consumer(BlockingQueue<Integer> queue) {
31+
this.queue = queue;
32+
}
33+
34+
@Override
35+
public void run() {
36+
while (true) {
37+
try {
38+
Integer value = queue.take();
39+
System.out.println("Consumer consumed: " + value);
40+
Thread.sleep(2000);
41+
} catch (Exception e) {
42+
Thread.currentThread().interrupt();
43+
System.out.println("Consumer interrupted");
44+
}
45+
}
46+
}
47+
}
48+
49+
public class PriorityBlockingQueueExample {
50+
public static void main(String[] args) {
51+
BlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
52+
53+
Thread producer = new Thread(new Producer(queue));
54+
Thread consumer = new Thread(new Consumer(queue));
55+
producer.start();
56+
consumer.start();
57+
58+
BlockingQueue<Integer> queue1 = new LinkedBlockingQueue<>();
59+
60+
BlockingQueue<String> queue2 = new PriorityBlockingQueue<>(11, Comparator.reverseOrder());
61+
62+
queue2.add("apple");
63+
queue2.add("banana");
64+
queue2.add("cherry");
65+
System.out.println(queue2);
66+
BlockingQueue<Integer> queue3 = new SynchronousQueue<>();
67+
}
68+
}

0 commit comments

Comments
 (0)