zoukankan      html  css  js  c++  java
  • 算法-03-Java 实现阻塞队列 字节三面算法题

    package com.example.polaris;
    
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class BlockedQueue<T> {
        private int size;
        private Object[] queue;
    
        final Lock lock = new ReentrantLock();
        // 条件变量:队列不满
        final Condition notFull = lock.newCondition();
        // 条件变量:队列不空
        final Condition notEmpty = lock.newCondition();
    
        private int index;
        private int removeIndex;
        private int currLen;
    
    
        public BlockedQueue(int size) {
            this.index = 0;
            this.removeIndex = 0;
            this.currLen = 0;
            this.size = size;
            queue = new Object[size];
        }
    
        // 入队
        public void push(T element) throws InterruptedException {
            lock.lock();
            try {
                while (currLen == size) {
                    System.out.println("队列已满,等待队列不满");
                    notFull.await();
                }
                queue[index] = element;
                if (++index == size) {
                    index = 0;
                }
                currLen++;
                notEmpty.signal();
            } finally {
                lock.unlock();
            }
        }
    
        // 出对
        public T pop() throws InterruptedException {
            lock.lock();
            try {
                while (currLen == 0) {
                    System.out.println("队列已空,等待队列不空");
                    notEmpty.await();
                }
                Object obj = queue[removeIndex];
                if (++removeIndex == size) {
                    removeIndex = 0;
                }
                currLen--;
                notFull.signal();
                return (T) obj;
            } finally {
                lock.unlock();
            }
        }
    
    }
    不要小瞧女程序员
  • 相关阅读:
    swift init继承问题
    CocoaPods 使用本地代码
    关于Xcode6 Segue 的疑问,没有解决!
    Cocos2d 学习资料推荐
    iOS8中 UILocalNotification 和 UIRemoteNotification 使用注意
    Cocos2d 初学基本知识
    iOS 和 Android 触摸事件传递
    iOS NSOperation的使用
    Android 相机对焦模式
    AES 推荐文章
  • 原文地址:https://www.cnblogs.com/shix0909/p/15032739.html
Copyright © 2011-2022 走看看