The easy way we can identify and reduce this problem to a producer-consumer problem is by identifying that we have a limited number of consumers and a infinite number of items being produced.This means we have to use a semaphore in order to keep track of how many produced items are currently being handled by consumers.Object class instead of using Blocking Queue for flow control.
Order: 9 being taken care of with 2 meals also ready.
Order: 4 being taken care of with 2 meals also ready.
Here is complete Java program to solve producer consumer problem in Java programming language.
In this program we have used wait and notify method from
The inner loop checks the capacity of a list, if list if full then it gives up the lock on the synchronized block and goes to 3.
In consumer method above, we again have an infinite outer loop which checks/consume a value from the list.Image you’re sitting in a busy restaurant waiting for some friends to arrive and you are watching the waiters/waitresses take food from the kitchen to tables.This is a classic example of the producer-consumer problem. Meaning there is a bound on waiters (consumers) and an unlimited supply of meals produced by the chiefs (producers).The consumer will know when data entered into the buffer for consuming and producer must stop producing when consumption rate is slow and the buffer is filled.To solve producer consumer problem, We need to take care few things like producer stop producing by either go to sleep or discard data.In producer method above, the value is initialized as 0.Inside this method, we have an infinite outer loop which contains synchronized block which ensures that at a time only producer or consumer thread runs.Order: 10 being taken care of with 1 meals also ready.Order: 1 being taken care of with 0 meals also ready.If we build an outline of the algorithm it would look as follows: Output: Order: 3 being taken care of with 0 meals also ready.Order: 5 being taken care of with 0 meals also ready.