我正在尝试使用生产者-消费者模式的等待通知来实现自己的阻塞队列。 如果元音的数量大于30%,则生产者将产生一个随机的字符串,而消费者将消费该字符串并对其进行计数。
队列:
public class Queue {
private LinkedList<String> queue;
private int size;
private Object notEmpty = new Object();
private Object notFull = new Object();
public Queue(int size) {
this.queue = new LinkedList<>();
this.size = size;
}
public synchronized void insert(String str) throws InterruptedException {
while (queue.size() == size) {
notFull.wait();
}
queue.add(str);
notEmpty.notifyAll();
}
public synchronized String remove() throws InterruptedException {
while (queue.isEmpty()) {
notEmpty.wait();
}
String str = queue.remove();
notFull.notifyAll();
return str;
}
}
制作人:
公共类Producer实现Runnable {
private Queue queue;
public Producer(Queue queue) {
this.queue = queue;
}
@Override
public void run() {
try {
queue.insert(StringUtils.generateRandomString((100000)));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
消费者:
public class Consumer implements Runnable {
private Queue queue;
public static int count;
public Consumer(Queue queue) {
this.queue = queue;
}
@Override
public void run() {
try {
String str = queue.remove();
if ((double) StringUtils.countVowels(str) / str.length() >= 0.3) {
count++;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
错误:
java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at com.mambu.assignment3.Queue.insert
at com.mambu.assignment3.Producer.run
问:我不明白为什么会出现此错误。