使用BlockingQueue阻塞队列实现生产者与消费者

BlockingQueue阻塞式队列

  1. 主要实现类:
    在这里插入图片描述
  2. 使用有界队列ArrayBlockingQueue实现生产者与消费者;
public class ArrayBlockingQueueTest {
    private static ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue(10);
    @Test
    public void test() {
        Runnable add = () -> {
            for (int i = 0; i < 100; i++) {
                try {
                    queue.put(i);
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Runnable delete = () -> {
            for (int i = 0; i < 100; i++) {
                try {
                    Integer poll = queue.take();
                    System.out.println(Thread.currentThread().getName() + ":" + poll);
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(add, "add");
        Thread thread1 = new Thread(delete, "delete1");
        Thread thread2 = new Thread(delete, "delete2");
        Thread thread3 = new Thread(delete, "delete3");
        thread.start();
        thread1.start();
        thread2.start();
        thread3.start();
        try {
            thread.join();
            while (queue.size() > 0) {
            }
        } catch (InterruptedException e) {
        }
    }
}
  1. 上述代码定义了ArrayBlockingQueue的队列大小为10,也就是说生产者生产满10个物品就会进入阻塞状态,直到消费者进行消费才可以继续生产;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值