Java:信号量:生产者消费者:线程和线程组

发布于 2024-12-08 11:06:35 字数 166 浏览 1 评论 0 原文

我已经为生产者和消费者实现了一个信号量类。

它工作正常,但我现在感觉我们使用notifyAll来通知唤醒或通知所有线程的线程。

我想知道是否有任何方法可以仅通知一组特定的组:例如生产者仅通知消费者线程,反之亦然,使用组或其他任何东西。

PS:我是java和线程的新手。

I have Implemented a semaphore class for producer and consumer.

It is working fine, But I am feeling now that we use notifyAll to notify the threads which awakes or notifies all the threads.

I want to know if there is any way in which we can notify only a particular set of groups: like producers only notify consumer threads and vice-versa using groups or anything else.

PS: I am new to java and Threading.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡写薰衣草的香 2024-12-15 11:06:35

在我看来,你就像是在重新发明轮子。 信号量可在 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 to notifyAll 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(), or producerObj.notifyAll(), depending on which group of threads you want to wake up.

温柔一刀 2024-12-15 11:06:35
Thread arr [] = new Thread[10];          
        ThreadGroup group = new ThreadGroup("test");
        group.enumerate(arr);
        group.notifyAll();
Thread arr [] = new Thread[10];          
        ThreadGroup group = new ThreadGroup("test");
        group.enumerate(arr);
        group.notifyAll();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文