阻塞队列模拟实现

①先写一个普通的队列(通过”循环队列的方式来实现“)

②加上线程安全(使用synchronized进行加锁控制)

③加上阻塞功能(put插入元素的时候,判定如果队列满了,在循环中进行wait;take取出元素的时候,判定如果队列为空,在循环中进行wait)

  //①先写循环队列
    private int[] elems = new int[1000];
    private volatile int size = 0;
    private int head = 0;
    private int tail = 0;

    //②加上线程安全(使用synchronized进行加锁控制)
    //③加上阻塞功能(put插入元素的时候,判定如果队列满了,在循环中进行wait;take取出元素的时候,判定如果队列为空,在循环中进行wait)
    public void put(int value) throws InterruptedException {
        synchronized (this) {
            while (size == elems.length) {
                wait();
            }
            elems[tail] = value;//每次把新数值放在tail所在位置
            tail = (tail + 1) % elems.length;//求余数。循环队列的特色
            size++;
            notifyAll();
        }
    }

    public int take() throws InterruptedException {
        int ret = 0;
        synchronized (this) {
            while (size == 0) {
                wait();
            }
            ret = elems[head];//队列遵循”先进先出“,所以从对头取元素
            head++;
            if (head == elems.length) {
                head = 0;
            }
            size--;
            notifyAll();
        }
        return ret;
    }

    public synchronized int size() {
        return size;
    }

    //测试代码
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue blockingQueue = new BlockingQueue();
            Thread customer = new Thread(() -> {
                while (true) {
                    try {
                        int value = blockingQueue.take();
                        System.out.println("消费元素" + value);//消费者——从阻塞队列中取元素
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, "消费者");
            customer.start();

            Thread producter = new Thread(() -> {
                Random random = new Random();
                while (true) {
                    try {
                        int num = random.nextInt(100);
                        System.out.println("生产元素" + num);//生产者——从阻塞队列中添加元素
                        blockingQueue.put(num);
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, "生产者");
        producter.start();
        customer.join();
        producter.join();
        }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值