Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 线程安全队列类出现问题。具体来说,除了例外_Java_Multithreading_Exception - Fatal编程技术网

Java 线程安全队列类出现问题。具体来说,除了例外

Java 线程安全队列类出现问题。具体来说,除了例外,java,multithreading,exception,Java,Multithreading,Exception,我使用的是线程安全队列类,并且我定义的insert方法有问题。缓冲区存储一个数组(elementData),该数组使用开始/结束变量来知道从队列中添加/删除内容的位置。它是线程安全的,所以它使用同步方法,所以我可以让多个线程引用同一个缓冲区 public class Buffer<T> { private T[] elementData; private int elementCount; private int st

我使用的是线程安全队列类,并且我定义的insert方法有问题。缓冲区存储一个数组(elementData),该数组使用开始/结束变量来知道从队列中添加/删除内容的位置。它是线程安全的,所以它使用同步方法,所以我可以让多个线程引用同一个缓冲区

public class Buffer<T> {
    private T[] elementData;                     
    private int elementCount;
    private int start;                                      
    private int end;

    // Additional fields

    // Code to instantiate a Buffer, other methods (e.g. delete)

    public synchronized void insert(T t) throws InterruptedException {
        while (elementCount == elementData.length) {
            wait();
        }
        end = (end + 1) % elementData.length;
        elementData[end] = t;
        elementCount++;
        notifyAll();
    }

    public static void main(String[] args) {
        Buffer<Integer> b = new Buffer();
        b.insert(3);
    }
}

编译异常是因为
insert
方法可能抛出InterruptedException(即使不是故意抛出),因此调用它的每个方法都必须使用try/catch块,即使从未出现错误:

public static void main(String[] args) {
    Buffer<Integer> b = new Buffer();
    try {
        b.insert(3);
    } catch(InterruptedException ie) {
        //error handling
        e.printStackTrace();
    }
}
publicstaticvoidmain(字符串[]args){
缓冲区b=新缓冲区();
试一试{
b、 插入(3);
}捕获(中断异常ie){
//错误处理
e、 printStackTrace();
}
}
public static void main(String[] args) {
    Buffer<Integer> b = new Buffer();
    try {
        b.insert(3);
    } catch(InterruptedException ie) {
        //error handling
        e.printStackTrace();
    }
}