In computing,
In the
The producer’s job is to generate data, put it into the buffer and start again.
At the same time, the consumer’s job is consuming the data, one piece at a time and removing it from the buffer.
The producer–consumer problem occurs when the producer try to add data into the buffer if it’s full and the same consumer try to remove data from an empty buffer.
Solution of Producer & Consumer
The solution for the producer must go to sleep if the buffer is full and the consumer must consume data.
Once the data is consumed it removes from the buffer by consumer process. Consumer process also notifies the producer, to starts fill the buffer again.
Similarly, the consumer process must go to sleep if it finds the buffer is empty and the producer puts data into the buffer.
Ones the data is filled into buffer by producer process it also notifies the Consumer, to starts consume the data from buffer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | class Item { int n; boolean condition = false; synchronized int get() { while(!condition) try { wait(); } catch(InterruptedException e) { System.out.println("Exception caught"); } System.out.println("Got: " + n); condition = false; notify(); return n; } synchronized void put(int x) { while(condition) try { wait(); } catch(InterruptedException e) { System.out.println("Exception caught"); } n = x; condition = true; System.out.println("Put: " + n); notify(); } } class Producer implements Runnable { Item q; Producer(Item q1) { q = q1; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) { q.put(i++); } } } class Consumer implements Runnable { Item q; Consumer(Item q1) { q = q1; new Thread(this, "Consumer").start(); } public void run() { while(true) { q.get(); } } } public class PCDemo { public static void main(String args[]) { Item q = new Item(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | Press Control-C to stop. Put: 0 Got: 0 Put: 1 Got: 1 Put: 2 Got: 2 Put: 3 Got: 3 Put: 4 Got: 4 Put: 5 Got: 5 Put: 6 Got: 6 Put: 7 Got: 7 Put: 8 Got: 8 |
Description : In the above program there are four classes: Item, Producer, Consumer and
Item: the class is trying to synchronize.
Producer: produces the data.
Consumer: consumes the data produced by producer class.
In the above program we can see that, producer process producess the data and consumed by consuner process, then again a producer process producess a new data and consumed by consumer process and so on.
To stop the execution we have to pess ”Ctrl+C”.