生产者消费者模式(java)

package com.juc.mq;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author zzyuan
 * @create 2022-04-14 15:28
 */
@Slf4j(topic = "c.Test21")
public class Test21 {
    public static void main(String[] args) {
        MessageQueue mq = new MessageQueue(2);

        for (int i = 0; i < 4; i++) {
            int id = i;
            new Thread(()->{
                mq.put(new Message(id,"val-"+id));
            },"生产者").start();
        }
        
        new Thread(()->{
            while (true){
                try {
                    Thread.sleep(1000);//每隔1秒去mq中取消息
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message message = mq.take();
            }
        },"消费者").start();
    }
}

@Slf4j(topic = "c.MessageQueue")
class MessageQueue{

    private LinkedList<Message> queue;
    private int capacity;

    public MessageQueue(int capacity) {
        this.queue = new LinkedList<>();
        this.capacity = capacity;
    }



    //获取消息
    public Message take(){
        synchronized (queue){
            //检查队列是否为null
            while (queue.isEmpty()){
                try {
                    log.debug("队列为空,消费者线程等待");
                    queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //从队列的头部获取消息返回
            Message message = queue.removeFirst();
            log.debug("消费者消费一条消息{}",message);
            queue.notifyAll();
            return message;
        }
    }

    //存入消息
    public void put(Message message){
        synchronized (queue){
            while (queue.size() == capacity){
                try {
                    log.debug("队列以满,生产者等待");
                    queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(message);
            log.debug("生产出一个消息{}",message);
            queue.notifyAll();
        }
    }

}

final class Message{
    private int id;
    private Object object;

    public Message(int id, Object object) {
        this.id = id;
        this.object = object;
    }

    public int getId() {
        return id;
    }


    public Object getObject() {
        return object;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", object=" + object +
                '}';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值