Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Producers/Consumer

  Asked By: Leon    Date: Jul 19    Category: Java    Views: 883
  

i only need to ,, ask about a subject of Producer/Consumer
What if i need to have 2 producers each of these producers put such
a value whith a different synchronized function and the consumer
consumes the both item produced by the 2 producers each after another
how many falgs i need for these producers/Consumer i mean the boolean
flag (set value ) and what is the things that leads me to numbers of
flags .. thanks and hope you can understand my question if not
contact me again

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Sonya Flores     Answered On: Jul 19

i need to ask about the Producer/Consumer paradigm implemented
in the above code ..(This code implements 2 functions put/get for use
in the classes producer/consumer, and we used a buffer (value set) as
a flag which in turn lock or notify each thread ) this code only is a
one to one put  and get; what if we need to implement for example a
different version of the put method .. i.e say we use the same
function firstly with one argument and then we'll implement it using
2 arguments so what 'll be the job to do with the (value set) ... to
let the get() implemented by the consumer to consumes all puted value
for both method put(int n) and put(int n, int y) for example
(polling).. thanks for more information ... tell me



implementation of a producer and consumer.
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
- 208 -
public void run() {
while(true) {
q.get();
}
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

 
Didn't find what you were looking for? Find more on Producers/Consumer Or get search suggestion and latest updates.