-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerConsumerDemo.java
More file actions
62 lines (56 loc) · 2.25 KB
/
ProducerConsumerDemo.java
File metadata and controls
62 lines (56 loc) · 2.25 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
// 5. PRODUCER-CONSUMER PROBLEM - Coordinating threads producing and consuming data
// Problem: Producer must wait if buffer is full, Consumer must wait if buffer is empty
public class ProducerConsumerDemo {
static class Buffer {
private final int[] buffer = new int[3]; // Limited buffer size
private int count = 0; // Current items in buffer
// Produce an item - wait if buffer is full
public synchronized void produce(int value) throws InterruptedException {
while (count == buffer.length) {
System.out.println("Buffer FULL - Producer waiting...");
wait(); // Wait for consumer to consume
}
buffer[count++] = value;
System.out.println("Produced: " + value + " (Buffer size: " + count + "/" + buffer.length + ")");
notifyAll(); // Notify consumer
}
// Consume an item - wait if buffer is empty
public synchronized int consume() throws InterruptedException {
while (count == 0) {
System.out.println("Buffer EMPTY - Consumer waiting...");
wait(); // Wait for producer to produce
}
int value = buffer[--count];
System.out.println("Consumed: " + value + " (Buffer size: " + count + "/" + buffer.length + ")");
notifyAll(); // Notify producer
return value;
}
}
public static void main(String[] args) {
Buffer buffer = new Buffer();
// Producer thread
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
buffer.produce(i * 10);
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// Consumer thread
Thread consumer = new Thread(() -> {
try {
for (int i = 0; i < 5; i++) {
buffer.consume();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producer.start();
consumer.start();
}
}