Skip to content

Instantly share code, notes, and snippets.

@gourab5139014
Last active August 29, 2015 14:10
Show Gist options
  • Save gourab5139014/d1d4aa427886a277b677 to your computer and use it in GitHub Desktop.
Save gourab5139014/d1d4aa427886a277b677 to your computer and use it in GitHub Desktop.
Producer Consumer Problem in Java using Blocking Queue
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProducerConsumerPattern
{
public static void main(String args[])
{
BlockingQueue sharedQueue = new LinkedBlockingQueue<>();
Thread prodThread = new Thread(new Producer(sharedQueue));
Thread consThread = new Thread(new Consumer(sharedQueue));
prodThread.start();
consThread.start();
}
}
class Producer implements Runnable
{
private final BlockingQueue sharedQueue;
public Producer(BlockingQueue sharedQueue){
this.sharedQueue = sharedQueue;
}
@Override
public void run()
{
for(int i=0;i<10;i++)
{
try {
System.out.println("Produced: "+i);
sharedQueue.put(i);
}catch(InterruptedException e)
{
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e);
}
}
}
}
class Consumer implements Runnable
{
private final BlockingQueue sharedQueue;
public Consumer(BlockingQueue sharedQueue){
this.sharedQueue = sharedQueue;
}
@Override
public void run()
{
while(true)
{
try {
System.out.println("Consumed : "+sharedQueue.take());
} catch (InterruptedException ex) {
Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment