Producer Consumer Problem with Blocking Queue in Java.
Producer consumer problem is one of the most important problems which is asked in many interviews. Simplest way to solve this problem is to use Blocking Queue. Code can be viewed here.
import java.io.File;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumer {
public static void main(String args[]) {
// Creating shared object
BlockingQueue<String> sharedQueue = new LinkedBlockingQueue<String>(2);
// Note the Same sharedQueue is being passed to Producer as well as
// Consumer
// Creating Producer and Consumer Thread
Thread prodThread = new Thread(new Producer(sharedQueue), "ProcuerThread");
Thread consThread = new Thread(new Consumer(sharedQueue), "ConsumerThread");
// Starting producer and Consumer thread
prodThread.start();
consThread.start();
}
}
// Producer Class in java
class Producer implements Runnable {
private final BlockingQueue<String> sharedQueue;
public Producer(BlockingQueue<String> sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
String baseFilePath = "/inputfiledirectory";
try {
File baseDir = new File(baseFilePath);
for (File file : baseDir.listFiles()) {
if (file.isFile()) {
System.out.println("Producing file" + file.getName());
sharedQueue.put(file.getAbsolutePath());
Thread.sleep(1000);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// Consumer Class in Java
class Consumer implements Runnable {
private final BlockingQueue<String> sharedQueue;
public Consumer(BlockingQueue<String> sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
while (true) {
try {
String path = sharedQueue.take();
System.out.println("Consuming file :" + path);
new LineWordCount().calculate(path);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Comments
Post a Comment