import lombok.extern.slf4j.Slf4j;
import java.util.LinkedList;
@Slf4j
public class Test7 {
public static void main(String[] args) {
MessageQueue messageQueue = new MessageQueue(2);
for (int i = 0; i < 3; i++) {
int id = i;
new Thread(()->{
messageQueue.put(new Message(id,"1323"));
},"生产者"+i).start();
}
new Thread(()->{
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message take = messageQueue.take();
}
},"消费者").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.info("队列为空,消费者线程等待");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//从头部获取消息返回
Message message = list.removeFirst();
log.info("已消费消息");
list.notifyAll();
return message ;
}
}
//存入消息
public void put(Message message) {
synchronized (list) {
while (capcity == list.size()) {
try {
log.info("队列已满,生产者线程等待");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.addLast(message);
log.info("已生产消息");
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;
}
}