Array BlockingQueue 입대 소스 코드 분석

2712 단어 JAVA 기초
Array BlockingQueue 작업 원리:
기본 데이터 구조 Object [] 배열 은 선 입 선 출 (FIFO) 의 원칙 에 따라 생산자 와 소비자 모델 을 바탕 으로 하 는 경계 있 는 대열 이다.
   /** Main lock guarding all access */
    final ReentrantLock lock;//    

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

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


    /**      null,      
     * Throws NullPointerException if argument is null.
     *
     * @param v the element
     */
    private static void checkNotNull(Object v) {
        if (v == null)
            throw new NullPointerException();
    }



   /**     
     * Inserts element at current put position, advances, and signals.
     * Call only when holding lock.
     */
    private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();//  
    }

    /**     
     * Extracts element at current take position, advances, and signals.
     * Call only when holding lock.
     */
    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;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();//  
        return x;
    }


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


    //     :              ,    。
   /**
     * Inserts the specified element at the tail of this queue, waiting
     * for space to become available if the queue is full.
     *
     * @throws InterruptedException {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    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();
        }
    }



한 업무 에서        Object object = new Object();이게 끝 표시 로 판단 이 됩 니 다.

좋은 웹페이지 즐겨찾기