种类
| 类名 | 特性 |
|---|
| ArrayBlockingQueue | 由数组结构组成的有界阻塞队列 |
| LinkedBlockingQueue | 由链表结构组成的有界的阻塞队列(有界,默认大小 Integer.MAX_VALUE,相当于无界) |
| PriorityBlockingQueue | 支持优先级排序的无界阻塞队列 |
| DelayQueue | 使用优先级队列实现的延迟无界阻塞队列 |
| SynchronousQueue | 不存储元素的阻塞队列,即单个元素的队列,生产一个,消费一个,不存储元素,不消费不生产 |
| LinkedTransferQueue | 由链表结构组成的无界阻塞队列 |
| LinkedBlockingDeque | 由链表结构组成的双向阻塞队列 |
方法
| 常用方法 | 描述 |
|---|
| add(E e) | 将指定的元素插入此队列中,如果没有可用的空间,则抛出异常。 |
| offer(E e) | 将指定的元素插入此队列中,如果可以在不违反容量限制的情况下立即执行,则成功返回 true,否则返回 false。 |
| put(E e) | 将指定的元素插入此队列中,如果队列已满,则一直等待直到有空间可用。 |
| remove() | 检索并删除此队列的头部,如果队列为空,则抛出异常。 |
| poll() | 检索并删除此队列的头部,如果队列为空,则返回 null。 |
| take() | 检索并删除此队列的头部,如果队列为空,则一直等待直到有元素可用。 |
| element() | 检索但不删除此队列的头部,如果队列为空,则抛出异常。 |
| peek() | 检索但不删除此队列的头部,如果队列为空,则返回 null。 |
并发生产消费
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;public class Test {private static int count = 0;private static int pSum = 0;private static int cSum = 0;private static final BlockingQueue queue = new ArrayBlockingQueue<Integer>(10);static class Producer implements Runnable {@Overridepublic void run() {try {for (int i = 0; i < 12; i++) {Thread.sleep(200L);queue.put(1);synchronized (Test.class) {count++;pSum++;System.out.println(Thread.currentThread().getName() + "生产者,目前有" + count + ",共生产" + pSum);}}} catch (Exception e) {e.printStackTrace();}}}static class Consumer implements Runnable {@Overridepublic void run() {try {for (int i = 0; i < 12; i++) {Thread.sleep(200L);queue.take();synchronized (Test.class) {count--;cSum++;System.out.println(Thread.currentThread().getName() + "消费者,目前有" + count + ",共消费" + cSum);}}} catch (Exception e) {e.printStackTrace();}}}public static void main(String[] args) throws Exception{new Thread(new Producer()).start();new Thread(new Producer()).start();new Thread(new Producer()).start();Thread.sleep(2000L);new Thread(new Consumer()).start();new Thread(new Consumer()).start();new Thread(new Consumer()).start();}
}