-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerConsumerWithLock.java
More file actions
92 lines (76 loc) · 2.6 KB
/
ProducerConsumerWithLock.java
File metadata and controls
92 lines (76 loc) · 2.6 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
85
86
87
88
89
90
91
92
package kb.concurrent.problems;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumerWithLock implements ProducerConsumer {
private final int MAX_SIZE = 10;
private final Random rand = new Random();
Queue<Integer> queue = new LinkedList<>();
ReentrantLock lock = new ReentrantLock();
Condition isNotFull = lock.newCondition();
Condition isNotEmpty = lock.newCondition();
// Produce an item
@Override
public void produce() {
try {
lock.lock();
while (queue.size() == MAX_SIZE) {
System.out.println(Thread.currentThread().getName() + " -> waiting state.");
isNotFull.await();
}
// produce an item and add to the queue
int num = rand.nextInt(100);
System.out.println(Thread.currentThread().getName() + "-> add: " + num);
queue.add(num);
isNotEmpty.signalAll();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.unlock();
}
}
// Consume an item
@Override
public void consume() {
try {
lock.lock();
while (queue.size() == 0) {
isNotEmpty.await();
}
// remove an item from the queue
System.out.println(Thread.currentThread().getName() + "-> remove: " + queue.poll());
isNotFull.signalAll();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ProducerConsumerWithLock pc = new ProducerConsumerWithLock();
// Create producer threads
for (int i = 0; i < 15; i++) {
Thread th = new Thread(() -> pc.produce());
th.setName("Producer " + i);
th.start();
}
// Create consumer threads
for (int i = 0; i < 10; i++) {
Thread th = new Thread(() -> pc.consume());
th.setName("Consumer " + i);
th.start();
}
try {
Thread.sleep(1000);
System.out.println("Final queue size: " + pc.queue.size());
// Thread.currentThread().join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}