1. 程式人生 > 實用技巧 >scala 之 函式

scala 之 函式

一、阻塞佇列說明

ArrayBlockingQueue是個底層以陣列實現為基礎的阻塞佇列,由於該阻塞佇列的建構函式中都有capacity,所以它是一個有界阻塞佇列。

常用方法和區別如下:

丟擲異常 特殊值 阻塞
插入
// 放入元素,如果佇列滿了,則丟擲異常
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");

}

真正呼叫的是父類AbstractQueue.add(E e)方法

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(); } }
如果佇列滿了,返回false
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(); } }

如果佇列滿了,則阻塞等待

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

如果佇列為空,則拋NoSuchElementException();

public E poll() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return (count == 0) ? null : dequeue();
    } finally {
        lock.unlock();
    }
}

如果佇列為空,返回null

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

如果佇列為空,則阻塞等待

讀取
public E element() {
    E x = peek();
    if (x != null)
        return x;
    else
        throw new NoSuchElementException();
}

如果對列為空,則拋NoSuchElementException();

public E peek() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return itemAt(takeIndex); // null when queue is empty
    } finally {
        lock.unlock();
    }
}

佇列為空,返回null

不可用
上述3個方法在AbstractQueue中 上述3個方法在ArrayBlockingQueue中 底層使用了Condition佇列