In this program we will use ArrayBlockingQueue.
FoodProducer.java
package com.techbyteslearn.lab.concurrent;
import java.util.concurrent.BlockingQueue;
public class FoodProducer implements Runnable {
private BlockingQueue<String> producerQueue = null;
public FoodProducer(BlockingQueue<String> queue) {
producerQueue = queue;
}
@Override
public void run() {
try {
producerQueue.put("Drinks");
Thread.sleep(2000);
producerQueue.put("Chocolates");
Thread.sleep(2000);
producerQueue.put("Fruits");
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
FoodConsumer.java
package com.techbyteslearn.lab.concurrent;
import java.util.concurrent.BlockingQueue;
public class FoodConsumer implements Runnable {
private BlockingQueue<String> consumerQueue = null;
public FoodConsumer(BlockingQueue<String> consumerQueue) {
this.consumerQueue = consumerQueue;
}
@Override
public void run() {
try {
System.out.println(consumerQueue.take());
System.out.println(consumerQueue.take());
System.out.println(consumerQueue.take());
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
MainFoodProcess.java
package com.techbyteslearn.lab.concurrent;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class MainFoodProcess {
public static void main(String[] args) throws InterruptedException {
final BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
FoodProducer producer = new FoodProducer(queue);
FoodConsumer consumer = new FoodConsumer(queue);
new Thread(producer).start();
new Thread(consumer).start();
Thread.sleep(3000);
}
}
Output:
DrinksChocolatesFruits
ArrayBlockingQueue has a capacity of 2, while the producer adds three items. The put() method blocks when the queue is full until the consumer takes an item from the queue.