Created
December 4, 2011 17:34
-
-
Save vishr/1430779 to your computer and use it in GitHub Desktop.
Simplest Producer-Consumer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
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