Skip to content

Instantly share code, notes, and snippets.

@GorvGoyl
Created July 12, 2015 21:08
Show Gist options
  • Save GorvGoyl/413a22db13a95281eae0 to your computer and use it in GitHub Desktop.
Save GorvGoyl/413a22db13a95281eae0 to your computer and use it in GitHub Desktop.
Producer Consumer problem - Solution using BlockingQueue() in Java
import java.util.concurrent.*;
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
Producer(BlockingQueue<Integer> q){
this.queue=q;
}
public void run() {
//produce messages
for(int i=1; i<11; i++){
try {
Thread.sleep(i);
queue.put(i);
System.out.println("Produced "+i);
} catch (InterruptedException e) {
}
}
}
}
class Consumer implements Runnable{
private BlockingQueue<Integer> queue;
Consumer(BlockingQueue<Integer> q){
this.queue=q;
}
public void run() {
try{
int i;
//consuming messages until exit message(10) is received
while(true){
Thread.sleep(10);
i = queue.take();
System.out.println("Consumed- "+i);
if(i==10) break;
}
}catch(InterruptedException e) {
}
}
}
public class ProducerConsumerService {
public static void main(String[] args) {
//Creating BlockingQueue of size 10
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
//starting producer to produce messages in queue
new Thread(producer).start();
//starting consumer to consume messages from queue
new Thread(consumer).start();
System.out.println("Producer and Consumer has been started");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment