阻塞队列的实现

public class Test1 {
static class BlockingQueue{
//普通队列实现方式两种:1.基于链表2.基于数组
private int[] array = new int[1000];
//head和tail构成一个前闭后开区间 当两者重合的时候,可能表示队列空或者满
private int head = 0;
private int tail = 0;
private int size = 0;

    //队列的基本操作:1.入队列2.出队列3.取队首元素
    //对于阻塞队列来说只之前入队列和出队列

    //入阻塞队列
    public  void put(int value) throws InterruptedException {
        synchronized (this) {
            if (size == array.length){
                wait();
            }
            //把value放在队尾即可
            array[tail] = value;
            tail++;
            if (tail == array.length){
                tail = 0;
            }
            size++;
            notify();
        }
    }


    //出阻塞队列
    public  int take() throws InterruptedException {
        int ret = array[head];
        synchronized (this) {
            if (size == 0){
                wait();
            }
            if (head == array.length){
                head = 0;
            }
            size--;
            notify();
        }
        return ret;
    }

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值