Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java multithreading on producer-consumer

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.

like image 972
Kevin Avatar asked Apr 05 '13 07:04

Kevin


People also ask

What is producer-consumer problem in multithreading?

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.

How do you solve producer-consumer problem in Java?

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.

What is thread Producer and Consumer?

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).

Is Java good for multithreading?

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.

How can we solve consumer problem by using wait () and notify () method?

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.


1 Answers

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.

like image 65
JB Nizet Avatar answered Oct 10 '22 21:10

JB Nizet