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();
        }
    }
相关文章
相关标签/搜索