-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathBlockingQueueSimpleExample.java
More file actions
56 lines (51 loc) · 2.32 KB
/
Copy pathBlockingQueueSimpleExample.java
File metadata and controls
56 lines (51 loc) · 2.32 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
package org.alxkm.patterns.collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* This class demonstrates the usage of a blocking queue in a producer-consumer scenario.
* A blocking queue with a capacity of 5 is created using ArrayBlockingQueue.
* A producer thread is created, which continuously adds elements to the blocking queue.
* The producer puts elements into the queue using the put() method. If the queue is full,
* the put() method blocks until space becomes available.
* A consumer thread is created, which continuously removes elements from the blocking queue.
* The consumer takes elements from the queue using the take() method. If the queue is empty,
* the take() method blocks until elements become available.
* Both producer and consumer threads run in parallel, simulating the production and consumption
* of elements from the blocking queue. Elements produced are printed with "Produced" prefix,
* and elements consumed are printed with "Consumed" prefix, along with their respective values.
*/
public class BlockingQueueSimpleExample {
public static void main(String[] args) {
// Create a blocking queue with a capacity of 5
BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(5);
// Producer thread
Thread producer = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
// Put elements into the queue
blockingQueue.put(i);
System.out.println("Produced: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// Consumer thread
Thread consumer = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
// Take elements from the queue
int value = blockingQueue.take();
System.out.println("Consumed: " + value);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// Start the producer and consumer threads
producer.start();
consumer.start();
}
}