The producer- consumer Problem in java
It is an evergreen synchronization problem in operating system. It has two entries. They are
- · Producer
- · Consumer
Producer is the one, which generates the item and adds it to
a shared region. Consumer is the one which retrieves the item from the shared
region and processes it.
So, synchronization plays a vital role here.
To handle this problem, the method “BlockingQueue” is used.
Technical implementation:
This
implementation creates two threads Producer and Consumer as Runnable.
- A private final BlockingQueue as integer. In the constructor, initialise the value.
- In the run() method,insert the value for queue and make the thread to sleep for some time.
- Similarly, do the above steps for Consumer thread also.
- Finally, in the main() function, create objects for queue. Using these objects, start the
- Threads.
Program:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
class Producer implements Runnable {
private final
BlockingQueue<Integer> queue1;
public
Producer(BlockingQueue<Integer> queue1) {
this.queue1 =
queue1;
}
@Override
public void run()
{
for (int i =
1; i <= 5; i++) {
try {
System.out.println("Produced: " + i);
queue1.put(i); // inserts item to the queue
Thread.sleep(1000); // Delay
} catch
(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class Consumer implements Runnable {
private final
BlockingQueue<Integer> queue1;
public
Consumer(BlockingQueue<Integer> queue1) {
this.queue1 =
queue1;
}
@Override
public void run()
{
while (true) {
try {
Integer item = queue1.take(); // Retrieves item
System.out.println("Consumed: " + item);
Thread.sleep(1500); // Delay
} catch
(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public class ProducerConsumerEg {
public static void
main(String[] args) {
BlockingQueue<Integer> queue1 = new
LinkedBlockingQueue<>(3);
Thread
producer1 = new Thread(new Producer(queue1));
Thread
consumer1 = new Thread(new Consumer(queue1));
producer1.start();
consumer1.start();
}
}
Output:
C:\raji\blog>javac ProducerConsumerEg.java
C:\raji\blog>java ProducerConsumerEg
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Produced: 5
Consumed: 4
Consumed: 5
This is the way of creating Producer consumer Problem in
java. Hope, you are understanding about the concept. Keep Coding!!!
Comments
Post a Comment