Created
February 6, 2013 16:53
-
-
Save karthikmit/4723958 to your computer and use it in GitHub Desktop.
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
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