-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProducerConsumerProblemBlockingQueueDemo.java
74 lines (54 loc) · 1.79 KB
/
ProducerConsumerProblemBlockingQueueDemo.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
63
64
65
66
67
68
69
70
71
72
73
74
package com.codecafe.concurrency.threadsignalling;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
// Producer and Consumer problem
// producer produces messages at a faster rate than the consumer can consume
// Revision of the original solution - use BlockingQueue instead of using our own MessageQueue
class _Producer implements Runnable {
BlockingQueue<String> queue;
public _Producer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
String message = "message #" + i;
try {
// Inserts the specified element into this queue, waiting if necessary for space to become available
queue.put(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sent - " + message);
}
}
}
class _Consumer implements Runnable {
BlockingQueue<String> queue;
public _Consumer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
String message;
try {
// Retrieves and removes the head of this queue, waiting if necessary until an element becomes available
message = queue.take();
System.out.println("received - " + message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ProducerConsumerProblemBlockingQueueDemo {
public static void main(String[] args) {
// buffer limit is set to 3
BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
Thread producerThread = new Thread(new _Producer(queue));
Thread consumerThread = new Thread(new _Consumer(queue));
producerThread.start();
consumerThread.start();
}
}