java arrayblockingqueue examples

www.ig‮aeditfi‬.com

ArrayBlockingQueue is a class in Java that implements the BlockingQueue interface. It is a thread-safe, bounded queue that stores elements in an array. Here are some examples of how to use ArrayBlockingQueue in Java:

  1. Create an ArrayBlockingQueue with a specified capacity.
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
  1. Add an element to the queue using the put() method. This method blocks if the queue is full.
queue.put("item");
  1. Retrieve and remove the head of the queue using the take() method. This method blocks if the queue is empty.
String item = queue.take();
  1. Check if the queue is empty using the isEmpty() method.
boolean empty = queue.isEmpty();
  1. Check if the queue is full using the remainingCapacity() method.
int remainingCapacity = queue.remainingCapacity();
boolean full = remainingCapacity == 0;
  1. Iterate over the elements in the queue using the iterator() method.
for (String item : queue) {
    System.out.println(item);
}

Here's an example that demonstrates how to use ArrayBlockingQueue in Java:

import java.util.concurrent.ArrayBlockingQueue;

public class ArrayBlockingQueueExample {
    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(10);

        Thread producer = new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    String item = "item " + i;
                    queue.put(item);
                    System.out.println("Produced: " + item);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread consumer = new Thread(() -> {
            while (true) {
                try {
                    String item = queue.take();
                    System.out.println("Consumed: " + item);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer.start();

        Thread.sleep(5000);
        producer.interrupt();
        consumer.interrupt();
        producer.join();
        consumer.join();
    }
}

In this example, we create an ArrayBlockingQueue with a capacity of 10. We also create two threads, a producer thread and a consumer thread. The producer thread adds 10 items to the queue using the put() method, while the consumer thread retrieves and removes items from the queue using the take() method. We start both threads, pause the main thread for five seconds, then interrupt both threads and wait for them to finish using join().