-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerConsumerWithBlockingQueue.java
More file actions
50 lines (40 loc) · 1.26 KB
/
ProducerConsumerWithBlockingQueue.java
File metadata and controls
50 lines (40 loc) · 1.26 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
package kb.concurrent.problems;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* This is the easiest Producer-Consumer problem solution. The Java
* BlockingQueue is designed to solve this type of problems.
*/
public class ProducerConsumerWithBlockingQueue implements ProducerConsumer {
private BlockingQueue<Integer> blockingQueue;
private final Random rand = new Random();
public ProducerConsumerWithBlockingQueue(int size) {
blockingQueue = new LinkedBlockingQueue<>(size);
}
@Override
public void produce() {
try {
blockingQueue.put(rand.nextInt());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void consume() {
try {
blockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ProducerConsumerWithBlockingQueue pc = new ProducerConsumerWithBlockingQueue(10);
try {
pc.blockingQueue.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}