Skip to content

Commit 9758a72

Browse files
committed
feat: add LinkedBlockingQueueExample demonstrating thread-safe producer-consumer pattern
Implemented LinkedBlockingQueueExample.java to illustrate producer-consumer coordination using LinkedBlockingQueue. Demonstrates blocking behavior with put() and take(), and includes examples of PriorityBlockingQueue and SynchronousQueue to compare bounded, unbounded, and synchronous queue types. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 0c48505 commit 9758a72

File tree

3 files changed

+68
-10
lines changed

3 files changed

+68
-10
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 LinkedBlockingQueueExample {
50+
public static void main(String[] args) {
51+
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
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+
}

Section 25 Collections Frameworks/Queue Interface/Linked Blocking Queue/src/Pending.java

Lines changed: 0 additions & 5 deletions
This file was deleted.

Section 25 Collections Frameworks/Queue Interface/Priority Blocking Queue/src/Pending.java

Lines changed: 0 additions & 5 deletions
This file was deleted.

0 commit comments

Comments
 (0)