BolckingQueue 生产者-消费者记录

BolckingQueue 生产者-消费者记录

BlockingQueue是阻塞队列,利用ReentrantLock的接口实现 ,依据它的基本原理,我们可以实现经典的生产者与消费者模式:
生产者与消费者模式想必大家都知道,在这里引用下图做简单说明
图片引用来自https://blog.csdn.net/tugangkai/article/details/82849172
图片引用来自https://blog.csdn.net/tugangkai/article/details/82849172
在这实现个类似加工厂的流水线业务:
eg:1线生产商品,2线加工商品,也就是生产者-消费者模式
生产者:

package com;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 生产者
 * @author
 */
public class Producer implements Runnable{

    private BlockingQueue<String> stock;
    /**
     * 超时时间
     */
    private int timeOut;

    private String commodity;

    public Producer(BlockingQueue<String> stock, int timeOut, String commodity) {
        this.commodity = commodity;
        this.stock = stock;
        this.timeOut = timeOut;
    }


    @Override
    public void run() {
        while (true) {
            try {
                stock.put(commodity);
                System.out.println("Producer生产数据" + commodity + ";库存剩余:" + stock.size());
                Thread.sleep(timeOut);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

            }
        }
    }
}

消费者:

package com;

import java.util.concurrent.BlockingQueue;

/**
 * 消费者
 * @author
 */
public class Consumer implements Runnable{

    private BlockingQueue<String> stock;

    private String consumerName;

    public Consumer(BlockingQueue<String> stock, String consumerName) {
        this.stock = stock;
        this.consumerName = consumerName;
    }

    @Override
    public void run() {
        while (true){
            try {
                String take = stock.take();
                System.out.println(consumerName + ";Consumer消费数据" + take + ";库存剩余:" + stock.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

测试类:

public static void main(String[] args) {
        BlockingQueue<String> stock = new ArrayBlockingQueue<>(10);
        Producer producer1 = new Producer(stock, 1000, "QQ");
        Producer producer2 = new Producer(stock, 1000, "微信");

        Consumer consumer1 = new Consumer(stock, "李明");
        Consumer consumer2 = new Consumer(stock, "小明");

        Thread p1 = new Thread(producer1);
        Thread p2 = new Thread(producer2);

        Thread c1 = new Thread(consumer1);
        Thread c2 = new Thread(consumer2);

        p1.start();
        p2.start();
        c1.start();
        c2.start();
    }

菜鸟的小记,理解不深,大神勿喷,仅以此记录,方便后面查看。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值