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();
            }
        }
    
    }
    不要小瞧女程序员
  • 相关阅读:
    登录功能实现
    JavaScript中的apply()方法和call()方法使用介绍
    导致JSON无法解析的问题
    git
    Xcode 与 macOS 系统版本的兼容问题
    创建多个Target
    验证合法身份证
    Xcode 6创建预编译头文件.pch
    About In-App Purchase
    Xcode 6制作通用framework库
  • 原文地址:https://www.cnblogs.com/shix0909/p/15032739.html
Copyright © 2011-2022 走看看