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();
            }
        }
    
    }
    不要小瞧女程序员
  • 相关阅读:
    函数的定义
    函数名的本质
    函数进阶
    三元运算
    数据类型 补充
    安装python问题
    neo4j nosql图数据库学习
    ubutun lunix 64安装neo4j 图形数据库
    git error: object file .git/objects/b9/e269f50db2a3415cc8ad5ba40b82b9b6a13d45 is empty
    django orm 时间处理
  • 原文地址:https://www.cnblogs.com/shix0909/p/15032739.html
Copyright © 2011-2022 走看看