以生产者/消费者模式挂起消费者 [英] Suspend consumer in producer/consumer pattern
问题描述
我将生产者和消费者与BlockingQueue
相关联.
I have producer and consumer connected with BlockingQueue
.
消费者等待队列中的记录并对其进行处理:
Consumer wait records from queue and process it:
Record r = mQueue.take();
process(r);
我需要从其他线程暂停此过程一段时间.如何实施?
I need pause this process for a while from other thread. How to implement it?
现在我认为可以实现它,但这似乎是一个糟糕的解决方案:
Now I think implement it such, but it's looks like bad solution:
private Object mLock = new Object();
private boolean mLocked = false;
public void lock() {
mLocked = true;
}
public void unlock() {
mLocked = false;
mLock.notify();
}
public void run() {
....
Record r = mQueue.take();
if (mLocked) {
mLock.wait();
}
process(r);
}
推荐答案
我认为您的解决方案简单而优雅,并且您应该对其进行一些修改.我建议的修改是同步.
I think your solution is simple and elegant, and think you should keep it with some modifications. The modifications I propose are synchronization.
没有它,可能会(并且经常)发生线程干扰和内存一致性错误.最重要的是,您不能wait
或notify
放在您不拥有的锁上(如果您在synchronized
块中拥有它,则可以拥有它.)修复很容易,只需在您等待/通知的位置添加mLock
同步块.另外,当您从其他线程更改mLocked
时,您将需要对其进行标记 volatile .
Without it, thread interference and memory consistancy errors can (and very often does) occur. On top of that, you can't wait
or notify
on a lock you don't own (and you own it if you have it inside a synchronized
block..). The fix is easy, just add a mLock
synchronize block where you wait/notify on it. Also, as you're changing mLocked
from a different thread you will want to mark it volatile.
private Object mLock = new Object();
private volatile boolean mLocked = false;
public void lock() {
mLocked = true;
}
public void unlock() {
synchronized(mlock) {
mLocked = false;
mLock.notify();
}
}
public void run() {
....
Record r = mQueue.take();
synchronized(mLock) {
while (mLocked) {
mLock.wait();
}
}
process(r);
}
这篇关于以生产者/消费者模式挂起消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!