-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainBlockingQueue.java
More file actions
48 lines (41 loc) · 1.63 KB
/
Copy pathMainBlockingQueue.java
File metadata and controls
48 lines (41 loc) · 1.63 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
//package The-bounded-buffer-problem;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class MainBlockingQueue {
public static void main(String[] args) {
final int bufferSize = 10; // Default buffer size
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(bufferSize);
AtomicInteger producerCount = new AtomicInteger(0);
AtomicInteger consumerCount = new AtomicInteger(0);
CuiBlockingQueue gui = new CuiBlockingQueue(queue, producerCount, consumerCount);
Thread producerThread = new Thread(() -> {
while (true) {
try {
if (producerCount.get() > 0) {
queue.put((int) (Math.random()*100));
gui.log("Produced: " + queue.peek());
Thread.sleep(500);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
Thread consumerThread = new Thread(() -> {
while (true) {
try {
if (consumerCount.get() > 0) {
//int item = queue.take();
gui.log("Consumed: " + queue.take());
Thread.sleep(500); // Simulate work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
producerThread.start();
consumerThread.start();
}
}