• 3.3.6-1 ArrayBlockingQueue简单分析


    构造方法:public ArrayBlockingQueue(int capacity) {
    this(capacity, false);
    }

    public ArrayBlockingQueue(int capacity, boolean fair) {
    if (capacity <= 0)
    throw new IllegalArgumentException();
    this.items = new Object[capacity];
    lock = new ReentrantLock(fair);
    notEmpty = lock.newCondition();
    notFull = lock.newCondition();
    }

    ArrayBlockingQueue的内部元素都放在一个对象数组中 items /** The queued items */ final Object[] items;
    添加元素的时候用 offer()和put()方法。用offer方法的时候如果数组已经满了,那么会返回false。但是put方法
    如果数组满了的话那么他会一直等待,知道队列中有空闲的位置。
    offer方法源码:
    public boolean add(E e) {
    return super.add(e);
    }
    public boolean offer(E e) {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    lock.lock(); // 一直等到获取锁
    try {
    if (count == items.length) //假如当前容纳的元素个数已经等于数组长度,那么返回false
    return false;
    else {
    enqueue(e); // 将元素插入到队列中,返回true
    return true;
    }
    } finally {
    lock.unlock(); //释放锁
    }
    }
    put方法源码:
    public void put(E e) throws InterruptedException {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly(); //可中断的获取锁
    try {
    while (count == items.length) //当线程从等待中被唤醒时,会比较当前队列是否已经满了
    notFull.await(); //notFull = lock.newCondition 表示队列不满这种状况,假如现场在插入的时候
    enqueue(e); //当前队列已经满了时,则需要等到这种情况的发生。
    } finally { //可以看出这是一种阻塞式的插入方式
    lock.unlock();
    }
    }

    如果我们想要取出元素,那么我们可以采用 poll()和take()方法,如果队列中没有元素了,那么poll会返回null,但是take不会,他会一直等待,直到队列有可用的元素。

    poll()方法源码:

    public E poll() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
    return (count == 0) ? null : dequeue(); //假如当前队列中的元素为空,返回null,否则返回出列的元素
    } finally {
    lock.unlock();
    }
    }

    take源码:

    take方法和put方法相互对应,他一定要拿到一个元素,除非线程被中断。

    public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
    while (count == 0) //线程在刚进入 和 被唤醒时,会查看当前队列是否为空
    notEmpty.await(); //notEmpty=lock.newCondition表示队列不为空的这种情况。假如一个线程进行take
    return dequeue(); //操作时,队列为空,则会一直等到到这种情况发生。
    } finally {
    lock.unlock();
    }
    }

    peek源码:

    如前文所说,peek方法不会真正的从队列中删除元素,实际上只是取出头元素而已。

    public E peek() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
    return itemAt(takeIndex); // null when queue is empty
    // 实际上 itemAt 方法就是 return (E) items[i];
    //也就是说 返回 数组中的第i个元素。 } finally { lock.unlock(); }}
    remove源码:

    remove方法实现在Abstract方法中,很容易看懂,里面就是走的poll方法。

    public E remove() {
    E x = poll();
    if (x != null)
    return x;
    else
    throw new NoSuchElementException();
    }

    enqueue源码:

    我们再来看看真正得到入队操作,不然光看上面的截图也不明白不是。

    private void enqueue(E x) { //因为调用enqueue的方法都已经同步过了,这里就不需要在同步了
    // assert lock.getHoldCount() == 1;
    // assert items[putIndex] == null;
    final Object[] items = this.items;
    items[putIndex] = x; //putIndex是下一个放至元素的坐标
    if (++putIndex == items.length) //putIndex+1, 并且比较是否与数组长度相同,是的话,则从数组开头
    putIndex = 0; //插入元素,这就是循环数组的奥秘了
    count++; //当前元素总量+1
    notEmpty.signal(); //给等到在数组非空的线程一个信号,唤醒他们。
    }

    dequeue源码:

    当然,我们也要看一下出对的操作

    private E dequeue() {
    // assert lock.getHoldCount() == 1;
    // assert items[takeIndex] != null;
    final Object[] items = this.items;
    @SuppressWarnings("unchecked")
    E x = (E) items[takeIndex];
    items[takeIndex] = null; //将要取出的元素指向null 表示这个元素已经取出去了
    if (++takeIndex == items.length) //takeIndex +1,同样的假如已经取到了数组的末尾,那么就要重新开始取
    takeIndex = 0; //这就是循环数组
    count--;
    if (itrs != null)
    itrs.elementDequeued(); //这里实现就比较麻烦,下次单独出一个吧,可以看看源码
    notFull.signal(); //同样 需要给 等待数组不满这种情况的线程一个信号,唤醒他们。
    return x;
    }

    练习的例子:


    package BlockQueueTEst;

    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.BlockingDeque;
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.LinkedBlockingQueue;

    /**
    * Created by zzq on 2018/2/27.
    */
    public class BTest {
    static ArrayBlockingQueue<String> blockingQueue=new ArrayBlockingQueue<String>(3);
    private static class TestT implements Runnable{

    public void run() {
    try {
    System.out.println(blockingQueue.take());
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    ;
    }
    }
    private static class TestT2 implements Runnable{

    public void run() {
    blockingQueue.offer("1");
    }
    }
    // public static void main(String[] args) throws InterruptedException {
    // blockingQueue.offer("1");
    // blockingQueue.offer("2");
    // blockingQueue.offer("3");
    // blockingQueue.offer("4");
    // blockingQueue.poll();
    // blockingQueue.poll();
    //
    // blockingQueue.offer("5");
    // System.out.println(blockingQueue.peek());
    //
    //// LinkedBlockingQueue linkedBlockingQueue=new LinkedBlockingQueue();
    // }
    public static void main(String[] args) throws InterruptedException {
    Thread t1=new Thread(new TestT());
    Thread t2=new Thread(new TestT2());
    t1.start();
    Thread.sleep(2000);
    t2.start();
    }
    }


  • 相关阅读:
    代码大全2阅读笔记之最后总结
    web商品系统最终版
    web商品系统
    期末总结
    2020/12/13
    2020/12/12
    2020/12/11
    2020/12/10
    2020/12/09
    2020/12/08
  • 原文地址:https://www.cnblogs.com/anxbb/p/8477690.html
Copyright © 2020-2023  润新知