ArrayBlockingQueue class is Java concurrent and bounded blocking queue implementation backed by an array. It orders elements FIFO (first-in-first-out).
This Java example to put and take elements from ArrayBlockingQueue using blocking insertions and retrieval.
This Java example to put and take elements from ArrayBlockingQueue using blocking insertions and retrieval.
- The producer thread will wait when the queue is full. As soon as, an element is taken from the queue, it adds the element to the queue.
- The consumer thread will wait if the queue is empty. As soon as, there is a single element in the queue, it takes out the element.
Java ArrayBlockingQueue Example
Java array blocking queue producer-consumer example:import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class ArrayBlockingQueueExample {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue < Integer > priorityBlockingQueue = new ArrayBlockingQueue < > (5);
//Producer thread
new Thread(() - > {
int i = 0;
try {
while (true) {
priorityBlockingQueue.put(++i);
System.out.println("Added : " + i);
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
//Consumer thread
new Thread(() - > {
try {
while (true) {
Integer poll = priorityBlockingQueue.take();
System.out.println("Polled : " + poll);
Thread.sleep(TimeUnit.SECONDS.toMillis(2));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
Output:
Added : 1
Polled : 1
Added : 2
Polled : 2
Added : 3
Added : 4
Polled : 3
Added : 5
Added : 6
Polled : 4
Added : 7
Added : 8
Polled : 5
Added : 9
Array
Collection Framework
Java
Comments
Post a Comment