I have implemented producer and consumer problem with semaphore. I need a way that when there is no product for consuming , the current thread wait until a producer produce a product. please guide me.
Asked
Active
Viewed 64 times
0
-
And your current code is what? No code, no help... – fge Jan 09 '15 at 21:05
1 Answers
2
Check out Java's BlockingQueue
, it already supports this behavior.
Code taken from the JavaDoc linked above, as an example:
class Producer implements Runnable {
private final BlockingQueue queue;
Producer(BlockingQueue q) { queue = q; }
public void run() {
try {
while (true) { queue.put(produce()); }
} catch (InterruptedException ex) { ... handle ...}
}
Object produce() { ... }
}
class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue q) { queue = q; }
public void run() {
try {
while (true) { consume(queue.take()); }
} catch (InterruptedException ex) { ... handle ...}
}
void consume(Object x) { ... }
}
class Setup {
void main() {
BlockingQueue q = new SomeQueueImplementation();
Producer p = new Producer(q);
Consumer c1 = new Consumer(q);
Consumer c2 = new Consumer(q);
new Thread(p).start();
new Thread(c1).start();
new Thread(c2).start();
}
}

Todd
- 30,472
- 11
- 81
- 89