Java:信号量:生产者消费者:线程和线程组
我已经为生产者和消费者实现了一个信号量类。
它工作正常,但我现在感觉我们使用notifyAll来通知唤醒或通知所有线程的线程。
我想知道是否有任何方法可以仅通知一组特定的组:例如生产者仅通知消费者线程,反之亦然,使用组或其他任何东西。
PS:我是java和线程的新手。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,你就像是在重新发明轮子。 信号量可在
java.util.concurrent
包。此外,对于生产者/消费者数据结构,我建议您只需使用
BlockingQueue
。不管怎样,notify 方法会通知一位(未指定的)服务员。如果您确实需要特定的“命令”来让哪些信号量通过,我相信您必须
notifyAll
并“手动”确保只允许相关的信号量获取信号量。对于您的特殊情况,在我看来,您需要为生产者提供一套等待集,为消费者提供一套等待集。由于每个对象都有一个等待集,因此不可能仅通知使用一个对象的消费者(或生产者)。也许您想要的是拥有两个对象,一个由生产者获取,一个由消费者获取,然后执行
consumerObj.notifyAll()
或ProducerObj.notifyAll()
,取决于您要唤醒哪组线程。Seems to me like you're reinventing the wheel. Semaphores are available in the
java.util.concurrent
package.Besides, for a producer / consumer datastructure, I'd suggest you simply use a
BlockingQueue
.Anyway, the
notify
method notifies one (unspecified) waiter. If you indeed need a specific "order" on which ones to let through, I believe you would have tonotifyAll
and "manually" make sure only the relevant ones are allowed to acquire the semaphore.For you particular case, it seems to me like you need one wait-set for producers, and one wait-set for consumers. Since you have one wait set per object, it is impossible to notify only the consumers (or producers) using one object. Perhaps what you're after is having two objects, one acquired by producers, and one acquired by consumers, and then do
consumerObj.notifyAll()
, orproducerObj.notifyAll()
, depending on which group of threads you want to wake up.