views:

320

answers:

4

how to implement producer consumer problem with multiple producers and multiple consumers?? how should we create threads?? Give me some overall idea..

Thanks in advance

A: 

Create a producer and a consumer class both of which are extending Thread class, and call them whenever you need. Where did you get stuck?

sahs
Instead of extending `Thread`, I'd suggest implementing `Runnable` or `Callable<V>` and wrapping the `Runnable` in a `Thread` or scheduling the `Callable<V>` using an `Executor`.
justkt
@justkt that does the trick :). I didn't know that though. Is that for performance issues? Why do we not extend Thread?
sahs
In general I've always been under the impression that composition is to be preferred over inheritance. Having a Runnable that is part of a Thread is composition. Having a Thread subclass is inheritance. It's for maintainability purposes. From Sun "[Employing] a Runnable object, is more general, because the Runnable object can subclass a class other than Thread."
justkt
+2  A: 

Perhaps you should make use of goole more :-)

Try This article and this source code for more info.

Derek Clarkson
+3  A: 

Sun has a Concurrency tutorial that covers essential threading classes. There's information on Defining and Starting a Thread that should answer your how to create a thread question nicely.

justkt
A: 
ConcurrentQueue q = new ConcurrentQueue(100);

ExecutorService service = Executors.newFixedThreadPool(20);

service.execute(new Producer(q));

for (int i=0; i < 18; i++) {
    service.execute(new Consumer(q));
}

Where both Consumer and Producer are custom classes that extend Runnable and take a Queue as their constructor argument.

Gandalf
I guess the multiple consumers part of the question is left as an exercise for the reader?
justkt
Generally in the model the Producer is doing nothing more then queuing up job requests (very fast task) and so only one is needed. The consumers on the other hand take a job from the queue and then [possibly] do some long running task, thus more are needed to service the queue.
Gandalf
That's the normal Producers-Consumers problem I've seen, but the OP specifically mentioned multiple producers.
justkt
Ahh I didn't see that. I think he should be able to figure it out from this example:)
Gandalf