我正在尝试编写一个简单的生产者消费者程序,使用一个堆栈,一个生产者和多个消费者,
正如您在以下代码中看到的,我有一个启动线程的 PC 类。问题是在结果中我只看到一个消费者从堆栈中弹出。为什么会这样?为什么它不让其他消费者也从堆栈中弹出?
class PC{
static Stack<Integer> sharedStack = new Stack<Integer>();
final static int MAX_SIZE = 10;
public static void main(String[] args){
new PC();
}
public PC(){
new Thread(new Producer() , "Producer").start();
Consumer consumer = new Consumer();
for (int i = 1 ; i < 10 ; i++)
new Thread(consumer , "Consumer " + i).start();
}
class Producer implements Runnable{
Random rnd = new Random();
public void run() {
while(true){
synchronized (sharedStack) {
if (sharedStack.size() < MAX_SIZE){
int r = rnd.nextInt(1000);
System.out.println(Thread.currentThread().getName() + " produced :" + r);
sharedStack.push(r);
sharedStack.notifyAll();
}
}
}
}
}
class Consumer implements Runnable{
public void run() {
while (true){
synchronized(sharedStack){
if (sharedStack.isEmpty()){
try {
sharedStack.wait();
} catch (InterruptedException e) {e.printStackTrace();}
}
System.out.println(Thread.currentThread().getName() + " consumed :" + sharedStack.pop());
}
}
}
}
}