我是靠谱客的博主 疯狂花生,这篇文章主要介绍ArrayBlockingQueueDemo,现在分享给大家,希望可以做个参考。

public class ArrayBlockingQueueDemo<T> {

    private T[] items = (T[]) new Object[100];
    private int count,getIndex,putIndex = 0;

    private final ReentrantLock lock = new ReentrantLock();
    private final Condition notEmpty = lock.newCondition();
    private final Condition notFull = lock.newCondition();

    private T get(){
        lock.lock(); // 先上锁
        T obj = null;
        while(count == 0){
            try {
                notEmpty.await();
                obj = items[getIndex++];
                if(getIndex == items.length) getIndex = 0; //循环队列
                --count;
                notFull.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        return obj;
    }

    public void put(T t){
        lock.lock();
        while(count == items.length){
            try {
                notFull.await();
                items[putIndex++] = t;
                if(putIndex == items.length) putIndex = 0;
                ++count;
                notEmpty.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

最后

以上就是疯狂花生最近收集整理的关于ArrayBlockingQueueDemo的全部内容,更多相关ArrayBlockingQueueDemo内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(94)

评论列表共有 0 条评论

立即
投稿
返回
顶部