代码实现
import lombok.extern.slf4j.Slf4j;
import java.util.LinkedList;
public class 生产者消费者模式 {
public static void main(String[] args) {
MessageQueue queue = new MessageQueue(2);
for (int i = 0; i < 3; i++) {
int id = i;
new Thread(() -> {
queue.put(new Message(id,"值" + id));
},"生产者" + i).start();
}
new Thread(() -> {
while (true){
try {
Thread.sleep(1000);
Message take = queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"消费者").start();
}
}
//消息队列类,java线程间通信的类
@Slf4j
class MessageQueue{
//双向队列,消息的队列集合
private LinkedList<Message> list = new LinkedList<>();
//消息的容量
private int capcity;
public MessageQueue(int capcity) {
this.capcity = capcity;
}
//获取消息
public Message take(){
//检查队列是否为空
synchronized (list){
while(list.isEmpty()){
try {
log.debug("队列为空,消费者线程等待");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 从队列头部获取消息并返回
Message message = list.removeFirst();
log.debug("已消费消息 {}",message);
//将消息移除,队列不满了,唤醒生产线程
list.notifyAll();
return message;
}
}
//存入消息
public void put(Message message){
synchronized (list){
//检查队列是否已满
while(list.size() == capcity){
try {
log.debug("队列已满,生产者线程等待");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消息加入队列的尾部
list.addLast(message);
log.debug("已生产消息 {}",message);
//将消息添加到队列中,唤醒获取线程
list.notifyAll();
}
}
}
final 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;
}
@Override
public String toString() {
return "Message{" +
"id=" + id +
", value=" + value +
'}';
}
}
结果展示:
16:19:01.182 [生产者0] DEBUG MessageQueue - 已生产消息 Message{id=0, value=值0}
16:19:01.189 [生产者1] DEBUG MessageQueue - 已生产消息 Message{id=1, value=值1}
16:19:01.189 [生产者2] DEBUG MessageQueue - 队列已满,生产者线程等待
16:19:02.181 [消费者] DEBUG MessageQueue - 已消费消息 Message{id=0, value=值0}
16:19:02.181 [生产者2] DEBUG MessageQueue - 已生产消息 Message{id=2, value=值2}
16:19:03.181 [消费者] DEBUG MessageQueue - 已消费消息 Message{id=1, value=值1}
16:19:04.181 [消费者] DEBUG MessageQueue - 已消费消息 Message{id=2, value=值2}
16:19:05.181 [消费者] DEBUG MessageQueue - 队列为空,消费者线程等待