我创建了一个像这样的堆栈类。有时它会运行,有时会通过 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/