【发布时间】:2015-02-02 01:46:02
【问题描述】:
请在下面找到消费者生产者代码:
// 生产者
public boolean busy = false;
while (rst != null && rst.next()) {
while (queue.size() == 10) {
synchronized (queue) {
try {
log.debug("Queue is full, waiting");
queue.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
synchronized (queue) {
queue.add(/* add item to queue */);
busy = true;
queue.notifyAll();
}
}
// 消费者
try {
while (!busy) {
while (queue.isEmpty()) {
synchronized (queue) {
try {
log.debug("Queue is empty, waiting");
queue.wait();
} catch (InterruptedException ex) {
ex.getMessage();
}
}
}
synchronized (queue) {
item = queue.remove();
log.debug("Consumed item" + ++count + " :" + item);
busy = false;
queue.notifyAll();
}
}
在我的生产者代码 sn-p 中,我已经同步了我用来添加元素的队列(链接阻塞队列),并使全局布尔变量忙到 true 并通知消费者。一旦队列大小为 10,生产者释放对象锁并进入等待状态。 对于我的消费者来说,一旦全局标志繁忙为真,消费者就会消耗元素并将标志变为假。 元素被适当地生产和消费。但我的代码没有从生产者消费者循环中终止,要执行的最终语句是“队列为空,等待”。 请告诉我如何修改我的代码和终止条件以退出循环。
【问题讨论】:
-
不要忽略
InterruptedException,而是将其作为停止信号。这意味着您不需要自己的busy标志,因为系统提供了一个供您使用。请参阅Brian Goetz: Dealing with InterruptedException,尤其是“实施可取消任务”部分。
标签: java multithreading concurrency thread-safety producer-consumer