forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProdConsumerSynchronized.java
More file actions
68 lines (51 loc) · 1.91 KB
/
ProdConsumerSynchronized.java
File metadata and controls
68 lines (51 loc) · 1.91 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
/**
* @program JavaBooks
* @description: ProdConsumerSynchronized
* synchronized版本的生产者和消费者,比较繁琐
* 能够支持2个生产者线程以及10个消费者线程的阻塞调用
* @author: mf
* @create: 2020/02/16 13:01
*/
package com.juc.queue;
import java.util.LinkedList;
public class ProdConsumerSynchronized {
private final LinkedList<String> lists = new LinkedList<>();
public synchronized void put(String s) {
while (lists.size() != 0) { // 用while怕有存在虚拟唤醒线程
// 满了, 不生产了
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lists.add(s);
System.out.println(Thread.currentThread().getName() + " " + lists.peekFirst());
this.notifyAll(); // 这里可是通知所有被挂起的线程,包括其他的生产者线程
}
public synchronized void get() {
while (lists.size() == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + lists.removeFirst());
this.notifyAll(); // 通知所有被wait挂起的线程 用notify可能就死锁了。
}
public static void main(String[] args) {
ProdConsumerSynchronized prodConsumerSynchronized = new ProdConsumerSynchronized();
// 启动消费者线程
for (int i = 0; i < 5; i++) {
new Thread(prodConsumerSynchronized::get, "ConsA" + i).start();
}
// 启动生产者线程
for (int i = 0; i < 5; i++) {
int tempI = i;
new Thread(() -> {
prodConsumerSynchronized.put("" + tempI);
}, "ProdA" + i).start();
}
}
}