-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathLinkedBlockingQueueExample.java
62 lines (51 loc) · 1.74 KB
/
LinkedBlockingQueueExample.java
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
package Day_41_LinkedBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class LinkedBlockingQueueExample {
public static void main(String[] args) {
// Create a LinkedBlockingQueue with a maximum capacity of 10
LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);
// Create and start producer and consumer threads
Thread producerThread = new Thread(new Producer(queue));
Thread consumerThread = new Thread(new Consumer(queue));
producerThread.start();
consumerThread.start();
}
}
class Producer implements Runnable {
private final LinkedBlockingQueue<Integer> queue;
public Producer(LinkedBlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 1; i <= 10; i++) {
// Put items into the queue
queue.put(i);
System.out.println("Produced: " + i);
Thread.sleep(100); // Simulate some work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
class Consumer implements Runnable {
private final LinkedBlockingQueue<Integer> queue;
public Consumer(LinkedBlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 1; i <= 10; i++) {
// Take items from the queue
Integer item = queue.take();
System.out.println("Consumed: " + item);
Thread.sleep(200); // Simulate some work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}