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")); }," producer "+ I).start(); } new Thread(()->{ while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Message take = messageQueue.take(); }}," consumer ").start(); @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(" queue empty, consumer thread waiting "); list.wait(); } catch (InterruptedException e) { e.printStackTrace(); Message = list.removeFirst(); Log.info (" consumed messages "); list.notifyAll(); return message ; Public void put(Message Message) {synchronized (list) {while (capCity == list.size()) {try { Log.info (" queue full, producer thread waiting "); list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.addLast(message); Log.info (" Produced 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; }}Copy the code