使用java实现简单的mq生产消费场景

场景:生产者生产口罩,消费者消费口罩

1、定义一个口罩的实体类

/**
 * 定义一个口罩的实体类
 */
public class KouZhao {
    private Integer id;
    private String type;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

 2、生产者代码

import java.util.concurrent.BlockingQueue;

/**
 * 生产者代码
 * @since 2022/10/25
 */
public class Producer implements Runnable{
    private BlockingQueue<KouZhao> queue;
    public Producer(BlockingQueue<KouZhao> queue){
        this.queue = queue;
    }
    private int index =0;
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(500);
                if(queue.remainingCapacity()<=0){
                    System.out.println("口罩堆积太多了,快来买吧...");
                }
                else{
                    KouZhao kouZhao = new KouZhao();
                    kouZhao.setId(index++);
                    kouZhao.setType("N95");
                    System.out.println("正在生产第"+index+"个口罩");
                    queue.add(kouZhao);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

3、消费者代码 

import java.util.concurrent.BlockingQueue;

/**
 * 消费者代码
 * @since 2022/10/25
 */
public class Consumer implements Runnable{
    private BlockingQueue<KouZhao> queue;
    public Consumer(BlockingQueue<KouZhao> queue){
        this.queue = queue;
    }
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(1000);
                System.out.println("正在准备购买口罩。。。");
                KouZhao kouZhao = queue.take();
                System.out.println("正在购买第"+kouZhao.getId()+
                        " "+kouZhao.getType()+"口罩");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

4、测试代码 


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 测试代码
 * @since 2022/10/25
 */
public class App {
    public static void main(String[] args) {
        BlockingQueue<KouZhao>queue = new ArrayBlockingQueue<>(10);

        new Thread(new Producer(queue)).start();
        new Thread(new Consumer(queue)).start();
    }
}

5、效果图

       1、 生产者生产的速度大于消费的速度时:当消息队列空间满了之后 生产者进入阻塞状态,直到消费者消费成功 消息队列有空余时间后,生产者会继续生产消息

        2、当消费者消费速度大于生产者速度时:当消息队列为空时,消费者进入阻塞状态,直到生产者生产消息成功放入到队列,消费者才能继续消费

 注: 具体测试效果可以通过调整生产者生产时间及消费者消费时间来查看

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值