我试图学习多线程,并尝试使用等待和通知的简单生产者/消费者模式。当我将模式拆分为两个消耗和一个产生时,我得到一个 ArrayIndexOutOfBounds 异常,该异常尚不清楚。该问题并不总是发生,有时会发生。我使用的是 I3 处理器。
我尝试添加一个 if 块来检查计数变量是否低于或高于声明的大小,但问题仍然存在。
private static Object key = new Object();
private static int[] buffer;
private volatile static Integer count;
static class Consumer {
void consume() {
synchronized (key) {
if (isEmpty()) {
try {
key.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer[--count] = 0;
key.notify();
}
}
public boolean isEmpty() {
return count == 0;
}
}
static class Producer {
void produce() {
synchronized (key) {
if (isFull()) {
try {
key.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer[count++] = 1;
key.notify();
}
}
public boolean isFull() {
return count == buffer.length;
}
}
public static void main(String[] args) throws InterruptedException {
buffer = new int[10];
count = 0;
Producer producer = new Producer();
Consumer consumer = new Consumer();
Runnable produce = () -> {
for (int i = 0; i < 1500; i++)
producer.produce();
System.out.println("Done producing");
};
Runnable consume = () -> {
for (int i = 0; i < 1300; i++)
consumer.consume();
System.out.println("Done consuming");
};
};
拉莫斯之舞
函数式编程
相关分类