多线程同步问题报错 求指导

用线程模拟生产者消费者去栈中存取字符
加了同步锁 两个线程时 不报错 生产者消费者加倍时就报错了

public class Stack {
private char[] cr = new char[5];
private int index = 0;

public void push(char c) {
    cr[index] = c;
    index++;
}

public char pop() {
    System.out.println("下标的值 " + index);
    index--;
    char c = cr[index];
    return c;
}

public boolean isEmpty() {
    System.out.println("数组为空判断 " + (index == 0));
    return index == 0;
}

public boolean isFull() {
    return index == 5;
}

}
线程模拟生产者
public class Producer extends Thread {

private Stack stack;

public Producer(Stack stack) {
    super();
    this.stack = stack;
}

public void run() {
    while (true) {
        // 随机生成a~z的英文字符,97 +[0,26)
        char c = (char) ('a' + new Random().nextInt(26));
        synchronized (stack) {
            if (stack.isFull()) {
                try {
                    stack.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            stack.push(c);
            System.out.println("压入字符" + c);
            stack.notifyAll();
        }
    }

}

}

线程模拟消费者
public class Consumer extends Thread {

private Stack stack;

public Consumer(Stack stack) {
    super();
    this.stack = stack;
}

public void run() {
    while (true) {
        synchronized (stack) {
            if (stack.isEmpty()) {
                try {
                    // 在栈对象上等待 收到通知后醒来继续执行
                    stack.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            char c = stack.pop();
            System.out.println("取出字符" + c);
            stack.notifyAll();
        }
    }

}

}

测试类 for循环 i小于1时不报错 i大于1就会报错
public class TestStack {

/**
 * @Title: main
 * @Description: 描述这个方法的作用
 * @param: @param args 参数说明
 * @return: void 返回类型
 * @throws
 */
public static void main(String[] args) {
    Stack stack = new Stack();
    for (int i = 0; i < 2; i++) {
        Producer producer = new Producer(stack);
        producer.start();
        Consumer consumer = new Consumer(stack);
        consumer.start();

    }

}

}

错误信息
Exception in thread "Thread-3" Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5 at com.dapang.test.Stack.pop(Stack.java:31)
at com.dapang.test.Consumer.run(Consumer.java:39)
java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5
at com.dapang.test.Stack.push(Stack.java:24)
at com.dapang.test.Producer.run(Producer.java:42)

两个consumer和两个producer。假设两个producer同时进入判断条件阻塞,一个comsumer消费了一条数据之后唤醒所有producer,那这两个producer都会跳出你的判断条件了,都执行push操作,造成你的stack溢出。

你这种实现线程的方式是有问题的,生产者,消费者模式要共享数据,线程的生成方式应该是实现Runnable接口,而不是继承Thread类,实现Runnable接口才能共享数据。

死锁了吧,stack stack =new stack()放入for循环中