java 多线程之-阻塞队列

自定义阻塞队列实现
本文介绍了一个自定义的阻塞队列实现,并通过ReentrantLock进行同步控制,展示了如何在多线程环境中安全地进行元素的添加和移除操作。
public class BlockingQueueApp {
    static class BlockingQueue<T>{
        private Queue<T> queue=new LinkedList<>();
        private int capacity;
        private Lock lock=new ReentrantLock();
        private Condition notFull=lock.newCondition();
        private Condition notEmpty=lock.newCondition();
        public BlockingQueue(int capacity){
            this.capacity=capacity;
        }
        public void put(T element) throws InterruptedException{
            lock.lock();
            try{
                while(queue.size()==capacity){
                    System.out.println("队列满了");
                    notFull.await();
                }
                queue.add(element);
                System.out.println("新增"+element);
                notEmpty.signal();
            }finally {
                lock.unlock();
            }
        }
        public T take()throws InterruptedException{
            lock.lock();
            try {
                while(queue.isEmpty()){
                    System.out.println("队列已空,不能再取");
                    notEmpty.await();
                }
                T item=queue.remove();
                System.out.println("取出了"+item);
                notFull.signal();
                return  item;
            }finally {
                lock.unlock();
            }
        }
    }
    public static void main(String[] args) throws InterruptedException{
        final BlockingQueue<Integer>blockingQueue=new BlockingQueue<>(10);
        final Random random=new Random();
        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        blockingQueue.put(random.nextInt(10));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                while (true){
                    try {
                       while (true){
                           blockingQueue.take();
                       }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread1.start();
        thread2.start();

    }
}

解析:

  1. 这里用了Lock lock=new ReentrantLock() 来同步代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值