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.
Seems to me like you’re reinventing the wheel. Semaphores are available in the
java.util.concurrentpackage.Besides, for a producer / consumer datastructure, I’d suggest you simply use a
BlockingQueue.Anyway, the
notifymethod notifies one (unspecified) waiter. If you indeed need a specific “order” on which ones to let through, I believe you would have tonotifyAlland “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.