java - 线程化 ArrayIndexOutofBoundException

标签 java multithreading generics

我创建了一个像这样的堆栈类。有时它会运行,有时会通过 ArrayIndexOutofBoundException 运行。线程中有什么问题?不太明白,请帮忙。

public class StackImpl<E> implements Stack<E>{

private E[] stackArray;

private int topOfStack;

public StackImpl(int size) {
    stackArray = (E[]) new Object[size];
    topOfStack = -1;
}

public synchronized void push(E e) {
    while (isFull()) {
        try {
            System.out.println("stack is full cannot add " + e);
            wait();
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        }
    }
    stackArray[++topOfStack] = e;
    System.out
            .println(Thread.currentThread() + " :notifying after pushing");
    notify();
}

public boolean isEmpty() {
    return topOfStack == 0;
}

public synchronized E pop() {
    while (isEmpty()) {
        try {
            System.out.println("stack is empty cannot pop ");
            wait();
        } catch (InterruptedException e) {

        }
    }
    System.out.println(topOfStack);
    E element = stackArray[topOfStack];
    stackArray[topOfStack--] = null;
    System.out.println(Thread.currentThread() + " notifying after popping");
    notify();
    return element;
}

public boolean isFull() {
    return topOfStack >= stackArray.length-1;
}

public static void main(String[] args) {
    final Stack<Integer> stack = new StackImpl<Integer>(10);
    (new Thread("Pusher") {
        public void run() {
            while (true) {
                stack.push(10);
            }
        }
    }).start();
    (new Thread("Popper") {
        public void run() {
            while (true) {
                stack.pop();
            }
        }
    }).start();
}

}

最佳答案

你设置

topOfStack = -1;

StackImpl 的构造函数中,但你的 isEmpty 方法检查是否为 0:

public boolean isEmpty() {
    return topOfStack == 0;
}

因此,如果推送器尚未添加任何值,则 while 循环将在第一次弹出时失败:

    public synchronized E pop() {
        while (isEmpty()) {
            try {
                System.out.println("stack is empty cannot pop ");
                wait();
            } catch (InterruptedException e) {

            }
        }

设置 topOfStack在构造函数中设置为 0,它应该可以工作。

编辑:想起来,改为更改 isEmpty -方法return topOfStack < 0; ,然后留下topOfStack = -1;在你的构造函数中...否则索引 0 中的元素永远不会弹出。

关于java - 线程化 ArrayIndexOutofBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9053320/

相关文章:

java - Java 中 Do-While 循环的 ExecutorService

c# - 具有特定类型的通用列表的扩展?

c#-4.0 - 为仅在运行时已知的类型创建已编译的 Expession.Lambda

java - 在用java编程时,我得到这个错误,有谁能告诉我到底出了什么问题吗?

java - 添加 FQDN 以在 SLF4J/Logback 中记录消息

java - 由 : java. lang.ClassNotFoundException : org. springframework.web.servlet.config.annotation.AsyncSupportConfigurer 引起

java - 如何从java中的FileOutPutStream获取标签的图像?

java - 比尔·普格·辛格顿(Bill Pugh Singleton),为什么线程安全?

java - Eclipse SWT : Display. 从同步方法调用syncExec()

swift - 在swift中创建通用变量字典