简单实现一个阻塞队列

仿照阻塞队列,实现自己的阻塞队列。( ArrayBlockingQueue )
代码如下,直接复制即可


/**
 *  仿照阻塞队列,实现自己的阻塞队列。( ArrayBlockingQueue )
 * 中间会使用到Lock接口,ReentrantLock,Condition 
 */

public class MyArrBlockingQueue {
    final Lock lock = new ReentrantLock();
    final Condition put_condition = lock.newCondition();
    final Condition take_condition = lock.newCondition();

    final Object[] items ;
    int put_index, take_index, count;
    public MyArrBlockingQueue(int capacity) {
        items = new Object[capacity];
    }

    public static void main(String[] args) {
        MyArrBlockingQueue queue  = new MyArrBlockingQueue(10);

        new Thread(() ->{//模拟往队列添加数据
            try {
                for (int i = 0; /*i<5 */;  i+=2) {
                    queue.put(i);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() ->{
            try {
                for (int i = 1; /*i<5 */;  i+=2) {
                    queue.put(i);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start(); //模拟往队列添加数据

        new Thread(() ->{ //模拟取数据
            try {
                while (true){
                    queue.take();
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }




   public void put(Object x) throws InterruptedException {
     lock.lock();
     try {
       while (count == items.length){
           put_condition.await();
           System.out.println("队列已经满了,阻塞put() 操作!!");
       }
       items[put_index] = x;
       System.out.println("当前队列数据:"+ Arrays.toString(items) + " 插入数据" +  x );

         if (++put_index == items.length)
           put_index = 0;
       ++count;
       take_condition.signal();
     } finally {
       lock.unlock();
     }
   }

   public Object take() throws InterruptedException {
     lock.lock();
     try {
       while (count == 0) 
         take_condition.await();
       Object x = items[take_index];
       if (++take_index == items.length){ //已经取到最后面的元素了
           take_index = 0;
           System.out.println("队列为空");
       }
       System.out.println("当前队列数据:"+ Arrays.toString(items) + "从队列取出" +  x );
       --count;
       put_condition.signal();
       return x;
     } finally {
       lock.unlock();
     }
   } 
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值