Producer Consumer problem implemented with the help of Blocking Queue concept instead of Wait and Notify
ProducerConsumer.java
This class will call Prouder and Consumer Class Thread.
package threading.multithreading;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumer {
public static void main(String[] args) {
//Blocking Queue allows elements in FIFO order
BlockingQueue sharedQueue = new LinkedBlockingQueue();
//Create thread for producer and consumer
Thread tProducer= new Thread(new Producer(sharedQueue));
Thread tConsumer= new Thread(new Consumer(sharedQueue));
tProducer.start();
tConsumer.start();
}
}
Producer.java
In this class, the producer is adding elements in the Queue.
package threading.multithreading;
import java.util.concurrent.BlockingQueue;
class Producer implements Runnable {
private BlockingQueue sharedQueue;
public Producer(BlockingQueue sharedQueue)
{
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
for (int i=0;i<5;i++)
{
try {
sharedQueue.put(i);
System.out.println("Produced "+i+" Size= "+sharedQueue.size());
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Consumer.java
In this class, Consumer is removing elements from the shared queue in FIFO order.
package threading.multithreading;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private BlockingQueue sharedQueue;
public Consumer(BlockingQueue sharedQueue2) {
this.sharedQueue=sharedQueue2;
}
@Override
public void run() {
while(true){
try {
System.out.println("Consumed: "+ sharedQueue.take() +" Size="+sharedQueue.size());
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
Output:
Produced 0 Size= 1
Consumed: 0 Size= 0
Produced 1 Size= 1
Consumed: 1 Size= 0
Produced 2 Size= 1
Consumed: 2 Size= 0
Produced 3 Size= 1
Consumed: 3 Size= 0
Consumed: 4 Size= 0
Produced 4 Size= 1
No comments:
Post a Comment