According to GeeksforGeeks-ProducerConsumerProblem, I am confused with the second exercise:
Try to make your program produce one item and immediately after that the consumer consumes it before any other item is produced by the consumer.
How to solve it? I think after the producer produces an item, we can just record the size after the producer add an item to the list. And while(list.size() == recordSize) wait(); Is it correct? Thank you for your time.
You can use a flag variable and everytime you want to produce an item you need to verify that this flag is false. (The flag is True if you have already produced an item so you can't produce another one until you know the consumer has handled it, You should protect the value of this flag with synchronized). now, if the flag is false, add an item and then
wait()
or else justwait()
for the consumer to consume it, and then usenotify()
in the consumer code to keep going. you should also usewait()
in the consumer code to wait until the producer produce an item, and then when you finish usenotify()
andwait()
to wait to new item.