Java Array Examples
- Java Array Simple Program
- Java Array - Create, Declare, Initialize and Print Examples
- How to Initialize an Array in Java in One Line
- What's the Simplest Way to Print a Java Array?
- Create and Initialize Two Dimensional Array in Java
- How to Check if Two Arrays are Equal in Java
- Java ArrayBlockingQueue Example
- Java Convert Array to Set
- Copying part of Array in Java Example
- Sorting an Array using Arrays.sort() Method
- Check Two Arrays are Deeply Equal
- Java Arrays.copyOf() Example - Copying an Array
- Java Arrays.binarySearch() Example - Searching an Array
- Java Arrays.asList() Example - Convert Array to ArrayList
- Java Convert Array to Stack Example
- Java Pyramid Examples
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.
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 : 9ArrayCollection FrameworkJava
Comments
Post a Comment