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();
            }
        }
    
    }
    不要小瞧女程序员
  • 相关阅读:
    Windows Mobile下创建cmwap接入点
    我的云之旅hadoop单机设置(2)
    ssh登录
    我的云之旅前言(1)
    实时搜索将是下一个核心
    cassandra索引目录
    图书大甩卖(操作系统、C语言、Linux) 已成交
    ehcache实例
    google推出语音搜索
    百姓网看起来还行
  • 原文地址:https://www.cnblogs.com/shix0909/p/15032739.html
Copyright © 2011-2022 走看看