作为练习,我编写了以下代码来练习生产者/消费者模式:
public class Producer implements Runnable {
BlockingQueue<Entity> entities;
public Producer(BlockingQueue<Entity> entities) {
this.entities = entities;
}
@Override
public void run() {
for (int i = 0; i <= 20; i++) {
Entity en = new Entity();
System.out.println("Producing entity: " + Integer.toString(i));
en.setName(Integer.toString(i));
entities.add(en);
}
}
}
public class Consumer implements Runnable {
BlockingQueue<Entity> entities;
public Consumer(BlockingQueue<Entity> entities) {
this.entities = entities;
}
@Override
public void run() {
try {
while (true) {
System.out.println("Consuming entity: "
+ entities.take().getName());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class MainPCClass {
BlockingQueue<Entity> entities = new LinkedBlockingQueue<Entity>(5);
public void start(){
//start the producer
new Thread(new Producer(entities)).start();
//start the consumer
new Thread(new Consumer(entities)).start();
}
}
我希望考虑到消费者中的上述 while(true),我的程序永远不会结束,并且消费者线程在生产者生产完所有内容后队列为空而被阻塞。这是为什么?我错过了什么吗?难道我做错了什么?我的程序运行和结束非常顺利。