BlockingQueue

實現方式是經過加鎖的方式老保證同步this

add:若是放得進去返回true,放不進去直接跑出異常線程

public boolean add(E e) {
        return super.add(e);
    }
  public boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }

put:放不進去則阻塞線程,沒有返回值code

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();
        }
    }

offer:放得進去返回true,放不進去返回false同步

public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)
                return false;
            else {
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }
相關文章
相關標籤/搜索