使用ArrayBlockingQueue实现一个生产者消费者模型

3 篇文章 0 订阅
2 篇文章 0 订阅

提供一个demo,仅供参考

public class ArrayBlockingQueueTestService {
    // 自定义线程池
    static ThreadPoolExecutor threadPoolExecutor =
            new ThreadPoolExecutor(2000, 5000, 100, TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue<>(1000));

    // 元素队列
    static ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(10);

    // 计数器,模拟存入的元素
    static AtomicInteger num = new AtomicInteger();

    public static void main(String[] args) {
        // 开启十个线程取元素
        for (int i = 0; i < 1000; i++) {
            threadPoolExecutor.execute(() -> {
                try {
                    // 休眠200ms
                    Thread.sleep(200);

                    // 线程名称
                    String name = Thread.currentThread().getName();
                    // 取出元素
                    String take = arrayBlockingQueue.take();
                    System.out.println(name + "取出元素:" + take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        // 开启十个线程存储元素
        for (int i = 0; i < 1000; i++) {
            threadPoolExecutor.execute(() -> {
                try {
                    // 休眠200ms
                    Thread.sleep(200);

                    // 线程名称
                    String name = Thread.currentThread().getName();
                    // 计数器
                    int andIncrement = num.getAndIncrement();
                    // 写入队列
                    arrayBlockingQueue.put(String.valueOf(andIncrement));
                    System.out.println(name + "存入元素:" + andIncrement);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        threadPoolExecutor.shutdown();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值