由数组支持的有界blocking queue 。 此队列命令元素FIFO(先进先出)。 队列的头部是队列中最长时间的元素。 队列的尾部是队列中最短时间的元素。 在队列的尾部插入新元素,队列检索操作获取队列头部的元素。
有些方法是继承的,所以一些方法在这个类 ArrayBlockingQueue 上面看不到。另外 add() 调用的 offer(),但是 offer() 不会报错,返回 null;remove() 调用的还是 poll(),但是 poll() 不会报错,返回 null。
方式 | 抛出异常 | 有返回值,不抛出异常 | 阻塞等待 | 超时等待 |
---|---|---|---|---|
添加 | boolean add(E e) | boolean offer(E e) | void put(E e) | boolean offer(E e, long timeout, TimeUnit unit) |
删除 | boolean remove() | E poll() | E take() | E poll (long timeout, TimeUnit unit) |
检查头元素 | E element() | E peek() |
package thread; import java.util.concurrent.*; /** * @Author 夏秋初 * @Date 2022/3/2 19:00 */ public class Test { public static void main(String[] args) throws InterruptedException { ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(5); for (int i = 0; i < 5; i++) { System.out.println(arrayBlockingQueue.add(String.valueOf(i))); } for (int i = 0; i < 5; i++) { System.out.println(arrayBlockingQueue.remove()); } } }
package thread; import java.util.concurrent.*; /** * @Author 夏秋初 * @Date 2022/3/2 19:00 */ public class Test { public static void main(String[] args) throws InterruptedException { ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(5); for (int i = 0; i < 5; i++) { System.out.println(arrayBlockingQueue.offer(String.valueOf(i))); } for (int i = 0; i < 5; i++) { System.out.println(arrayBlockingQueue.poll()); } } }
package thread; import java.util.concurrent.*; /** * @Author 夏秋初 * @Date 2022/3/2 19:00 */ public class Test { public static void main(String[] args) throws InterruptedException { ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(5); for (int i = 0; i < 5; i++) { arrayBlockingQueue.put(String.valueOf(i)); } for (int i = 0; i < 5; i++) { System.out.println(arrayBlockingQueue.take()); } } }
package thread; import java.util.concurrent.*; /** * @Author 夏秋初 * @Date 2022/3/2 19:00 */ public class Test { public static void main(String[] args) throws InterruptedException { ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(5); // for (int i = 0; i < 5; i++) { // arrayBlockingQueue.offer(String.valueOf(i), 5, TimeUnit.SECONDS); // } for (int i = 0; i < 5; i++) { System.out.println(arrayBlockingQueue.poll(5, TimeUnit.SECONDS)); } } }
package thread; import java.util.concurrent.*; /** * @Author 夏秋初 * @Date 2022/3/2 19:00 */ public class Test { public static void main(String[] args) throws InterruptedException { ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(5); for (int i = 0; i < 5; i++) { arrayBlockingQueue.offer(String.valueOf(i), 5, TimeUnit.SECONDS); } // for (int i = 0; i < 5; i++) { // System.out.println(arrayBlockingQueue.poll(5, TimeUnit.SECONDS)); // } System.out.println(arrayBlockingQueue.element()); System.out.println(arrayBlockingQueue.peek()); } }