Curriculum
ArrayBlockingQueue is a class that implements the BlockingQueue interface in Java. It is a bounded blocking queue that stores elements in an array. It means that the capacity of the queue is fixed and must be specified when the queue is created.
Here is an example of creating an ArrayBlockingQueue object with a capacity of 5:
BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
The ArrayBlockingQueue class provides the following methods:
Here is an example of using an ArrayBlockingQueue to implement a producer-consumer pattern:
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ProducerConsumerExample { public static void main(String[] args) { BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5); Thread producer = new Thread(() -> { for (int i = 1; i <= 10; i++) { try { queue.put(i); System.out.println("Produced: " + i); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread consumer = new Thread(() -> { while (true) { try { int num = queue.take(); System.out.println("Consumed: " + num); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }); producer.start(); consumer.start(); } }
In this example, the producer thread produces 10 integers and puts them into the queue using the put()
method. The consumer thread consumes the integers by taking them from the queue using the take()
method. The output shows that the producer and consumer threads are running concurrently and the producer blocks when the queue is full, and the consumer blocks when the queue is empty.