1、定义
- 与前面的保护性暂停中的GuardObject 不同,不需要产生结果和消费结果的线程一一对应
- 消费队列可以用来平衡生产和消费的线程资源
- 生产者仅负责产生结果数据,不关心数据该如何处理,而消费者专心处理结果数据
- 消息队列是有容量限制的,满时不会再加入数据,空时不会再消耗数据
- JDK中各种阻塞队列,采用的就是这种模式
2、实现
class Message {
private int id;
private Object value;
public Message(int id,Object value) {
this.id = id;
this.value = value;
}
public int getId() {
return id;
}
public Object getValue() {
return value;
}
}
class MessageQueue {
privae LinkedList<Message> list = new LinkedList<>();
private int capcity;
public MessageQueue(int capcity) {
this.capcity = capcity;
}
public Message take() {
synchronized(list) {
while(list.isEmpty()) {
try {
list.wait();
} catch (InterruptedExcption e) {
e.printStackTrace();
}
}
Message message = list.removeFirst();
list.notifyAll();
return message;
}
}
public void put(Message message) {
synchronized (list) {
while(list.size() == capcity) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.addLast(message);
list.notifyAll();
}
}
}