Skip to content

Commit 43bbbb6

Browse files
committed
feat: add SynchronousQueueExample demonstrating zero-capacity producer-consumer synchronization
Implemented SynchronousQueueExample.java to illustrate synchronized data exchange between producer and consumer threads using SynchronousQueue. Highlights blocking behavior of put() and take() operations with no internal buffering, and includes comparative references to LinkedBlockingQueue and PriorityBlockingQueue. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 30ecaa3 commit 43bbbb6

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
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 SynchronousQueueExample {
50+
public static void main(String[] args) {
51+
BlockingQueue<Integer> queue = new SynchronousQueue<>();
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)