What is this problem ?
Producer-Consumer problem is a classical concurrency problem.
Characteristics of the producer-consumer problem:
- Producer(s) produce items.
- Consumer(s) consume the items produced by the producer(s).
- Producer(s) finish production and let the consumers know that they are done.
Produced items will be left unconsumed, starting items will be skipped, consumption depends on whether the production began earlier or later than consumption attempts etc.
Note that in this producer-consumer problem the producer is running on a different thread than the ones on consumer.
Solution
The problem is to make sure that producer won’t try to add data into buffer if it is full and that the consumer won’t try to remove data from an empty buffer.
We can easily implement the producer consumer problem using the BlockingQueue.
A BlockingQueue already supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
Example - using BlockingQueue
Producer.java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
class Producer extends Thread {
BlockingQueue<String> bq;
Producer() {
bq = new ArrayBlockingQueue<String>(5);
}
public void run() {
for (int i = 0; i <= 10; i++) {
try {
System.out.println("adding str"+i);
bq.put("str"+i);
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
}
}
Consumer.java
import java.util.concurrent.TimeUnit;
class Consumer extends Thread {
Producer prod;
Consumer(Producer prod) {
this.prod = prod;
}
public void run() {
for(int i=0;i<10;i++) {
try {
System.out.println("received "+
prod.bq.poll(10, TimeUnit.SECONDS));
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
}
}
ProducerConsumer.java
public class ProducerConsumer {
public static void main(String[] args) {
Producer prod = new Producer();
Consumer cons = new Consumer(prod);
Thread t1 = new Thread(prod);
Thread t2 = new Thread(cons);
t2.start();
t1.start();
}
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.