grumpyboundedbuffer.java

来自「java concurrency in practice 源码. JAVA」· Java 代码 · 共 57 行

JAVA
57
字号
package net.jcip.examples;import net.jcip.annotations.*;/** * GrumpyBoundedBuffer * <p/> * Bounded buffer that balks when preconditions are not met * * @author Brian Goetz and Tim Peierls */@ThreadSafe        public class GrumpyBoundedBuffer <V> extends BaseBoundedBuffer<V> {    public GrumpyBoundedBuffer() {        this(100);    }    public GrumpyBoundedBuffer(int size) {        super(size);    }    public synchronized void put(V v) throws BufferFullException {        if (isFull())            throw new BufferFullException();        doPut(v);    }    public synchronized V take() throws BufferEmptyException {        if (isEmpty())            throw new BufferEmptyException();        return doTake();    }}class ExampleUsage {    private GrumpyBoundedBuffer<String> buffer;    int SLEEP_GRANULARITY = 50;    void useBuffer() throws InterruptedException {        while (true) {            try {                String item = buffer.take();                // use item                break;            } catch (BufferEmptyException e) {                Thread.sleep(SLEEP_GRANULARITY);            }        }    }}class BufferFullException extends RuntimeException {}class BufferEmptyException extends RuntimeException {}

⌨️ 快捷键说明

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