I am following a video tutorial on Java multi-threading. It introduces on using Java to implement the famous "Producer-consumer" problem.
It used wait() and notifyAll() to ensure the proper communication between producer threads and consumer threads.
The tutor intentionally created several producer threads while only one consumer threads, but he left a question unanswered: "It is always best practice to have equal number of producer and consumer threads, if there are more producer threads than consumer, there will be problems".
However, he didn't specify what that problem is. I personally imagine that would only be a situation that the basket is full. Could experts help here? Thanks.
In computing, the producer-consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue.
The producer cannot produce an item if the list is full and the consumer cannot consume it if the list is empty. We can solve the producer-consumer problem using semaphores, Semaphore is a thread synchronization construct. Semaphore is used to control the access to a shared resource with the help of a variable/counter.
The producer and consumer problem is one of the small collection of standard, well-known problems in concurrent programming. A finite-size buffer and two classes of threads, producers and consumers, put items into the buffer (producers) and take items out of the buffer (consumers).
Java has great support for multithreaded applications. Java supports multithreading through Thread class. Java Thread allows us to create a lightweight process that executes some tasks. We can create multiple threads in our program and start them.
You can use wait, notify, and notifyAll methods to communicate between threads in Java. For example, if you have two threads running in your programs like Producer and Consumer then the producer thread can communicate to the consumer that it can start consuming now because there are items to consume in the queue.
You could have any number of producers and any number of consumers.
If the producers produce too fast, the queue will fill up, until you get memory problems or the producers are forced to stay idle until there's some place left in the queue.
If the consumers consume too fast, they will stay idle most of the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With