Java ArrayBlockingQueue Example

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 fromArrayBlockingQueue 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:
importjava.util.concurrent.ArrayBlockingQueue;importjava.util.concurrent.TimeUnit;publicclassArrayBlockingQueueExample {publicstaticvoidmain(String[]args)throwsInterruptedException {ArrayBlockingQueue<Integer> priorityBlockingQueue=newArrayBlockingQueue < > (5);//Producer threadnewThread(()-> {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 threadnewThread(()-> {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 : 1Polled : 1Added : 2Polled : 2Added : 3Added : 4Polled : 3Added : 5Added : 6Polled : 4Added : 7Added : 8Polled : 5Added : 9









Comments