BlockingQueue is a Java interface that represents a queue that can block when attempting to dequeue an element, when the queue is empty, or when attempting to enqueue an element, when the queue is full.
Here's an example of how to use a BlockingQueue:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueExample {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
new Thread(producer).start();
new Thread(consumer).start();
}
}
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
queue.put(i);
System.out.println("Produced: " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
int num = queue.take();
System.out.println("Consumed: " + num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
In this example, the Producer and Consumer classes implement the Runnable interface and are meant to run concurrently in separate threads. The Producer class adds elements to the queue, and the Consumer class retrieves elements from the queue. When the queue is full, the put method will block until there is space in the queue. Similarly, when the queue is empty, the take method will block until there is an element to retrieve.
No comments:
Post a Comment