forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProdConsumerReentrantLock.java
More file actions
76 lines (66 loc) · 2.03 KB
/
ProdConsumerReentrantLock.java
File metadata and controls
76 lines (66 loc) · 2.03 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
/**
* @program JavaBooks
* @description: ProdConsumerReentrantLock
* @author: mf
* @create: 2020/02/16 13:43
*/
package com.juc.queue;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProdConsumerReentrantLock {
private LinkedList<String> lists = new LinkedList<>();
private Lock lock = new ReentrantLock();
private Condition prod = lock.newCondition();
private Condition cons = lock.newCondition();
public void put(String s) {
lock.lock();
try {
// 1. 判断
while (lists.size() != 0) {
// 等待不能生产
prod.await();
}
// 2.干活
lists.add(s);
System.out.println(Thread.currentThread().getName() + " " + lists.peekFirst());
// 3. 通知
cons.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void get() {
lock.lock();
try {
// 1. 判断
while (lists.size() == 0) {
// 等待不能消费
cons.await();
}
// 2.干活
System.out.println(Thread.currentThread().getName() + " " + lists.removeFirst());
// 3. 通知
prod.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ProdConsumerReentrantLock prodConsumerReentrantLock = new ProdConsumerReentrantLock();
for (int i = 0; i < 5; i++) {
int tempI = i;
new Thread(() -> {
prodConsumerReentrantLock.put(tempI + "");
}, "ProdA" + i).start();
}
for (int i = 0; i < 5; i++) {
new Thread(prodConsumerReentrantLock::get, "ConsA" + i).start();
}
}
}