⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 conditionboundedbuffer.java

📁 java concurrency in practice 源码. JAVA并发设计
💻 JAVA
字号:
package net.jcip.examples;import java.util.concurrent.locks.*;import net.jcip.annotations.*;/** * ConditionBoundedBuffer * <p/> * Bounded buffer using explicit condition variables * * @author Brian Goetz and Tim Peierls */@ThreadSafepublic class ConditionBoundedBuffer <T> {    protected final Lock lock = new ReentrantLock();    // CONDITION PREDICATE: notFull (count < items.length)    private final Condition notFull = lock.newCondition();    // CONDITION PREDICATE: notEmpty (count > 0)    private final Condition notEmpty = lock.newCondition();    private static final int BUFFER_SIZE = 100;    @GuardedBy("lock") private final T[] items = (T[]) new Object[BUFFER_SIZE];    @GuardedBy("lock") private int tail, head, count;    // BLOCKS-UNTIL: notFull    public void put(T x) throws InterruptedException {        lock.lock();        try {            while (count == items.length)                notFull.await();            items[tail] = x;            if (++tail == items.length)                tail = 0;            ++count;            notEmpty.signal();        } finally {            lock.unlock();        }    }    // BLOCKS-UNTIL: notEmpty    public T take() throws InterruptedException {        lock.lock();        try {            while (count == 0)                notEmpty.await();            T x = items[head];            items[head] = null;            if (++head == items.length)                head = 0;            --count;            notFull.signal();            return x;        } finally {            lock.unlock();        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -