Skip to content

Instantly share code, notes, and snippets.

@vishr
Created December 4, 2011 17:34
Show Gist options
  • Save vishr/1430779 to your computer and use it in GitHub Desktop.
Save vishr/1430779 to your computer and use it in GitHub Desktop.
Simplest Producer-Consumer
/**
*
*/
package com.qwata.concurrency;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author Vishal Rana
*
*/
public class ProducerConsumer {
private ExecutorService producers = Executors.newFixedThreadPool(100);
private ExecutorService consumers = Executors.newFixedThreadPool(100);
public static void main(String[] args) throws InterruptedException {
ProducerConsumer pc = new ProducerConsumer();
for (int i = 1; i <= 1000; i++) {
pc.producers.submit(pc.new Producer(i));
}
pc.producers.shutdown();
pc.producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
pc.consumers.shutdown();
pc.consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
class Producer implements Runnable {
private int data;
public Producer(int data) {
this.data = data;
}
public void run() {
ProducerConsumer pc = ProducerConsumer.this;
pc.consumers.submit(pc.new Consumer(data));
System.out.println("Producer sent: " + data);
}
}
class Consumer implements Runnable {
private int data;
public Consumer(int data) {
this.data = data;
}
public void run() {
System.out.println("Consumer received: " + data);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment