我有4个类:Main,Producer,Consumer和Buffer。缓冲区类包含圆形数组的实现(假设它可以工作)。生产者类添加到缓冲区数组,而消费者类从缓冲区数组中删除。 Main类为生产者和消费者创建线程。
在生产者类内部,如果缓冲区未满,它将添加到缓冲区中。如果已满,它将等待,直到使用者从阵列中移除某些东西为止。
在Consumer类中,如果缓冲区不为空,它将从其中删除一个项目。如果为空,则等待生产者向缓冲区中添加一些东西。
我遇到的问题是生产者将项目添加到数组中,但是每次通知消费者它已经添加到缓冲区时,消费者就处于等待状态。它永远不会继续其余的代码。
// Main.java
Buffer buffer = new Buffer(5); // creates a circular array of length 5.
// 10 is total number of items to be added
Producer p = new Producer(buffer,10); // uses random number generator for values
Consumer c = new Consumer(buffer,10);
p.start();
c.start();
p.join();
c.join();
public class Producer extends Thread {
...
public void run() {
...
while(true) {
synchronized(this) {
try {
while(buffer.isFull()) wait();
...
buffer.insert(val);
notify();
... // other stuff that eventually breaks the loop
} catch(InterruptedException e) {}
}
}
}
}
public class Consumer extends Thread {
...
public void run() {
while(true) {
synchronized(this) {
try {
while(buffer.isEmpty()) wait(); // its stuck here
...
buffer.remove();
notify();
... // other stuff that eventually breaks the loop
} catch (InterruptedException e) {}
}
}
}
}
// Inside Buffer.java
public void insert(int n) {
...
buffer[front] = n;
front++;
size++;
}
public int remove() {
...
temp = buffer[rear] = -1;
rear--;
size--;
return temp;
}
在生产者中,有一个print语句打印5个添加到缓冲区的值(缓冲区的最大大小),但此后什么也没有发生。生产者将值添加到数组,然后进入等待状态,但是消费者不执行任何操作,因为它仍然保持在等待状态。
我无法弄清楚为什么每次生产者向缓冲区添加内容时,生产者都会执行通知,而消费者却不继续进行。