blockQueue阻塞队列

阻塞队列的实现

  • ArrayBlockingQueue 实现了BlockingQueue接口,主要的变量是
  /*
     * Concurrency control uses the classic two-condition algorithm
     * found in any textbook.
     */

    /** Main lock guarding all access */
    final ReentrantLock lock;

    /** Condition for waiting takes */
    private final Condition notEmpty;

    /** Condition for waiting puts */
    private final Condition notFull;

put方法

public void put(E e) throws InterruptedException {
        //检查是否为空
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        //获取锁,非中断的情况,直到获取锁成功
        lock.lockInterruptibly();
        try {
            //判断是否满了
            while (count == items.length)
                //慢了的话,等着
                notFull.await();
            //添加元素    
            enqueue(e);
        } finally {
            //释放锁
            lock.unlock();
        }
    }

take 方法

 public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

condition生产者消费者的模型,类似blockingQueue的实现

package com.company;

import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangpeng
 */
public class ConditionDemo {
    private Queue<Object> queue;
    private ReentrantLock reentrantLock;
    //为空的时间
    private Condition empty;
    //满的时候
    private Condition notEmpty;
    private int size;

    /**
     * 存数据
     *
     * @param o
     * @throws InterruptedException
     */
    public void put(Object o) throws InterruptedException {
        if (o == null) {
            return;
        }
        reentrantLock.lockInterruptibly();
        try {
            if (queue.size() == size) {
                notEmpty.await();
            }
            queue.add(o);
            empty.signalAll();
        } finally {
            reentrantLock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        reentrantLock.lockInterruptibly();
        try {
            if (queue.size() == 0) {
                empty.await();
            }
            Object remove = queue.remove();
            notEmpty.signalAll();
            return remove;
        } finally {
            reentrantLock.unlock();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值