-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP56_ProducerConsumerThreadQueue.java
More file actions
76 lines (64 loc) · 2.48 KB
/
Copy pathP56_ProducerConsumerThreadQueue.java
File metadata and controls
76 lines (64 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package programs;
import java.util.LinkedList;
import java.util.Queue;
/**
* ============================================================
* PROGRAM 56: Multithreaded Producer-Consumer with wait() & notify()
* ============================================================
* Problem: WAP to implement the classic Producer-Consumer pattern
* using a shared bounded queue with `wait()` and `notifyAll()`.
* ============================================================
*/
class BoundedBuffer {
private final Queue<Integer> queue = new LinkedList<>();
private final int capacity;
public BoundedBuffer(int capacity) {
this.capacity = capacity;
}
public synchronized void produce(int value) throws InterruptedException {
while (queue.size() == capacity) {
System.out.println(" ⚠️ Buffer is FULL! Producer waiting...");
wait();
}
queue.offer(value);
System.out.printf(" 🟢 [PRODUCER] Produced item: %d (Buffer Size: %d)%n", value, queue.size());
notifyAll();
}
public synchronized int consume() throws InterruptedException {
while (queue.isEmpty()) {
System.out.println(" ⚠️ Buffer is EMPTY! Consumer waiting...");
wait();
}
int value = queue.poll();
System.out.printf(" 🔴 [CONSUMER] Consumed item: %d (Buffer Size: %d)%n", value, queue.size());
notifyAll();
return value;
}
}
public class P56_ProducerConsumerThreadQueue {
public static void main(String[] args) throws InterruptedException {
BoundedBuffer buffer = new BoundedBuffer(3);
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 6; i++) {
buffer.produce(i * 10);
Thread.sleep(150);
}
} catch (InterruptedException ignored) {}
});
Thread consumer = new Thread(() -> {
try {
for (int i = 1; i <= 6; i++) {
buffer.consume();
Thread.sleep(300); // Consumer is slower to test full buffer condition
}
} catch (InterruptedException ignored) {}
});
System.out.println("=== PRODUCER-CONSUMER CONCURRENCY DEMO ===");
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println("✓ All items produced and consumed safely without race conditions.");
}
}