阻塞队列

生产者消费者模式: 生产者消费者模式就是通过一个容器来解决生产者和消费者的强耦合问题。
具体工作方式: 生产者和消费者不会直接接触,而是通过一个阻塞队列来进行相互作用,生产者负责往里面放东西,而消费者负责取东西。当阻塞队列为空且消费者恰好要取的时候,此时消费者会调用wait方法阻塞,并通知生产者该往里面放东西了。反过来,生产者者发现队列已经满了的时候,会通知消费者。
代码示例:

public class 阻塞队列 {
    private static final int CAPCITY = 5;
    int[] arr = new int[CAPCITY];
    int firstNum = 0;
    int lastNum = 0;
    int size = 0;
    public synchronized void put(int element) throws InterruptedException{
        if(size != arr.length){
            wait();
        }
        arr[lastNum] = element;
        lastNum += 1;
        if(lastNum == arr.length){
            lastNum = 0;
        }
        size++;
        notifyAll();
    }
    public synchronized int take() throws InterruptedException{
        int element;
        if(size == 0){
            wait();
        }
        element = arr[firstNum];
        firstNum += 1;
        if(firstNum == arr.length){
            firstNum = 0;
        }
        size--;
        notifyAll();
        return element;
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值