-
Notifications
You must be signed in to change notification settings - Fork 29
/
Solution_2.java
113 lines (88 loc) · 2.88 KB
/
Solution_2.java
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package other_problem;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 生产者消费者
*/
public class Solution_2 {
// 1、定义一个Message类
public class Message {
private int code;
private String msg;
// Handler target;
public Message() {
}
public Message(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
// 2、定义一个IMessageQueue接口:包含next与enqueueMessage抽象方法
public interface IMessageQueue {
Message next() throws InterruptedException;
void enqueueMessage(Message message) throws InterruptedException;
}
// 3、阻塞队列LinkedBlockingQueue实现阻塞式生产者消费者模式:take/put 是阻塞方法
public class MessageQueue implements IMessageQueue {
private final BlockingQueue<Message> queue;
public MessageQueue(int cap) {
this.queue = new LinkedBlockingQueue<>(cap);
}
public Message next() throws InterruptedException {
return queue.take();
}
public void enqueueMessage(Message message) {
try {
queue.put(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 4、链表 + synchronized + wait/notifyAll + volatile变量 + 对象锁实现非阻塞式的生产者消费者模式
public class MessageQueue1 implements IMessageQueue {
private Queue<Message> queue;
private volatile int count;
private final Object BUFFER_LOCK = new Object();
public MessageQueue1(int cap) {
this.count = cap;
queue = new LinkedList<>();
}
@Override
public Message next() throws InterruptedException {
synchronized (BUFFER_LOCK) {
while (queue.size() == 0) {
BUFFER_LOCK.wait();
}
Message message = queue.poll();
BUFFER_LOCK.notifyAll();
return message;
}
}
@Override
public void enqueueMessage(Message message) throws InterruptedException {
synchronized (BUFFER_LOCK) {
while (queue.size() == count) {
BUFFER_LOCK.wait();
}
queue.offer(message);
BUFFER_LOCK.notifyAll();
}
}
}
}