bufferimpl.java

来自「英国帝国理工学院电脑系多线程课程教学材料之五 ---- 有限缓冲区范例」· Java 代码 · 共 36 行

JAVA
36
字号
package concurrency.buffer;

/*********************BUFFER*****************************/

public class BufferImpl<E> implements Buffer<E> {

    protected E[] buf;
    protected int in = 0;
    protected int out= 0;
    protected int count= 0;
    protected int size;

    public BufferImpl(int size) {
        this.size = size;
        buf = (E[])new Object[size];
    }

    public synchronized void put(E o) throws InterruptedException {
        while (count==size) wait();
        buf[in] = o;
        ++count;
        in=(in+1) % size;
        notifyAll();
    }

    public synchronized E get() throws InterruptedException {
        while (count==0) wait();
        E o = buf[out];
        buf[out]=null;
        --count;
        out=(out+1) % size;
        notifyAll();
        return (o);
    }
}

⌨️ 快捷键说明

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