-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockingQueueDemo.java
More file actions
84 lines (66 loc) · 2.3 KB
/
BlockingQueueDemo.java
File metadata and controls
84 lines (66 loc) · 2.3 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package concurrentCollection;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BlockingQueueDemo {
static final int capacity = 5;
static BlockingQueue<Integer> queue=new ArrayBlockingQueue<>(capacity);
public static void main(String[] args) {
try(ExecutorService ex= Executors.newFixedThreadPool(5)){
Producer producer=new Producer(queue);
Consumer consumer=new Consumer(queue);
ex.execute(producer);
ex.execute(producer);
ex.execute(producer);
ex.execute(consumer);
ex.execute(consumer);
ex.execute(consumer);
}
}
}
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
// Shared static counter for all producers
private static final AtomicInteger counter = new AtomicInteger();
Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
int product = counter.getAndIncrement(); // Get a unique number
queue.put(product);
System.out.println("Produced: " + product + " by " + Thread.currentThread().getName() + " Queue Size: " + queue.size());
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // good practice
// optionally exit the loop
}
}
}
}
class Consumer implements Runnable{
private BlockingQueue<Integer> queue;
Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run(){
while (true){
try{
queue.take();
System.out.println("Consumed: " + "by " + Thread.currentThread().getName()+" Queue Size: " + queue.size());
}catch (InterruptedException e){
throw new RuntimeException(e);
}
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}