Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Leon Hansen   on Jul 19 In Java Category.

  
Question Answered By: Sonya Flores   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.");
}
}

Share: 

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