Skip to content

Instantly share code, notes, and snippets.

@karthikmit
Created February 6, 2013 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save karthikmit/4723958 to your computer and use it in GitHub Desktop.
Save karthikmit/4723958 to your computer and use it in GitHub Desktop.
public class ProducerConsumerTest {
@Test
public void basicProducerComsumerTest() throws InterruptedException {
Producer producer = new Producer();
Consumer consumer = new Consumer();
Queue<String> prodConsQueue = new LinkedList<String>();
producer.setProductionQueue(prodConsQueue);
consumer.setProductionQueue(prodConsQueue);
producer.start();
consumer.start();
Thread.sleep(1000);
producer.terminate();
consumer.terminate();
producer.join();
consumer.join();
}
private class Producer extends Thread {
private volatile boolean stopProcessing = false;
private Queue productionQueue;
public void setProductionQueue(Queue productionQueue) {
this.productionQueue = productionQueue;
}
public void terminate() {
stopProcessing = true;
}
@Override
public void run() {
int index = 0;
while(!stopProcessing) {
index++;
productionQueue.add(new String("Product number - ") + Integer.toString(index));
}
}
}
private class Consumer extends Thread {
private volatile boolean stopProcessing = false;
private Queue productionQueue;
public void setProductionQueue(Queue productionQueue) {
this.productionQueue = productionQueue;
}
public void terminate() {
stopProcessing = true;
}
@Override
public void run() {
while(!stopProcessing) {
consume();
}
}
private void consume() {
String prod = (String)productionQueue.poll();
if(prod != null) {
System.out.println(prod);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment