006并发编程基础-wait/notify模拟BlockingQueue

本文详细介绍了如何使用wait/notify机制模拟BlockingQueue的put和take操作,通过自定义的MyBlockingQueue类,演示了线程间同步的过程。当队列满时,put操作将阻塞;当队列空时,take操作将阻塞,直到条件满足。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BlockingQueue的使用范围非常的广泛,比如线程池中的阻塞队列,阻塞的原因在于:
1.当队列的容量达到最大时,再加入元素就会处于阻塞状态,当有空位置时会自动加入
2.当队列的容量为最小时,取元素就会被阻塞,当容器中有元素时会自动取出。

这里使用wait/notify来模拟BlockingQueue中的put和take操作。

public class MyBlockingQueue {
    //构造一个队列容器
    private  LinkedList<Object> list=new LinkedList<>();
    //构造计数器
    private  AtomicInteger count=new AtomicInteger();
    //容器大小
    private final Integer minSize=0;
    private final Integer maxSize;

    public MyBlockingQueue(Integer maxSize) {
        this.maxSize = maxSize;
    }


    public synchronized  void put(Object obj)  {
        if(list.size()==maxSize){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.add(obj);
        count.addAndGet(1);
        this.notify();
    }
    public synchronized  Object take()  {
        if(list.size()==minSize){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Object res=list.removeFirst();
        count.decrementAndGet();
        this.notify();
        return res;
    }

    public void print(){
        for (Object obj : list) {
            System.out.println(obj);
        }
    }

    public static void main(String[] args) {
        MyBlockingQueue blockingQueue = new MyBlockingQueue(5);
        blockingQueue.put(1);
        blockingQueue.put(2);
        blockingQueue.put(3);
        blockingQueue.put(4);
        blockingQueue.put(5);
        new Thread(new Runnable() {
            @Override
            public void run() {
                blockingQueue.put(6);
                blockingQueue.put(7);
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer num = (Integer)blockingQueue.take();
                System.out.println("移除了元素: "+num);
                Integer num2 = (Integer)blockingQueue.take();
                System.out.println("移除了元素: "+num2);
            }
        }).start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("容器中现有元素为...");
        blockingQueue.print();

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员bling

义父,感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值