异步设计模式之生产者消费者
- 异步:将产生结果的类(生产者)与获取结果的类(消费者)解耦,生产者专注于生产,消费者专注于消费
- 采用消息队列来平衡生产者和消费者线程资源,不需要在一一对应了
- 队列满则生产者不在生产,队列空则消费者停止消费
class MessageQuque {
private LinkedList<Message> list = new LinkedList<>();
private int capcity;
public MessageQuque(int capcity) {
this.capcity = capcity;
}
public Message take() {
synchronized (list) {
while (list.isEmpty()) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.notifyAll();
return list.removeFirst();
}
}
public void put(Message message) {
synchronized (list) {
while (list.size() == capcity) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.addLast(message);
list.notifyAll();
}
}
}
final class Message {
private int id;
private Object value;
public int getId() {
return id;
}
public Object getValue() {
return value;
}
public Message(int id, Object value) {
this.id = id;
this.value = value;
}
@Override
public String toString() {
return "Message{" +
"id=" + id +
", value=" + value +
'}';
}
}