ArrayBlockingQueue
is one implementation of the java.util.concurrent.BlockingQueue
which internally store the queue elements inside an array. The ArrayBlockingQueue
can store elements for the size defined when the object is initialized, by the constructor. Once it size is defined it cannot be change or resize.
The code snippet below demonstrate the ArrayBlockingQueue
class. We initialize the queue to allow its internal array to store maximum of 64 elements.
package org.kodejava.example.util.concurrent;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ArrayBlockingQueueExample {
private BlockingQueue<String> sharedQueue = new ArrayBlockingQueue<>(64);
public static void main(String[] args) {
new ArrayBlockingQueueExample().createProducerConsumer();
}
private void createProducerConsumer() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName());
try {
sharedQueue.put("DATA");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "Producer Thread").start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.print(Thread.currentThread().getName() + "=> ");
try {
System.out.println(sharedQueue.take());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "Consumer Thread-1").start();
}
}
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
ArrayBlockingQueue in Java orders elements FIFO (first-in-first-out). The head of the queue is the element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time.