阻塞队列BlockingQueue的方法分类
方法类型 | 抛出异常 | 特殊值 | 阻塞 | 超时 |
---|
插入 | add(e) | offer(e) | put(e) | offer(e,time,unit) |
移除 | remove() | poll() | take() | poll(time,unit) |
检查 | element() | peek() | 不可用 | 不可用 |
| |
---|
抛出异常 | 当阻塞队列满时,再往队列里add插入元素会抛出异常。当阻塞队列为空时,再从队列里remove移除元素会抛异常 |
特殊值 | 插入方法,成功返回true,失败返回false。移除方法,成功返回出队列的元素,失败返回null |
一直阻塞 | 当阻塞队列满时,再往队列里put插入元素,队列会一直阻塞生产者线程直到put数据或响应中断退出。 当阻塞队列为空时,再从队列里take移除元素,队列会一直阻塞消费者线程直到队列可用 |
超时退出 | 当阻塞队列满时,队列会阻塞生产线程一定时间,超过限时后生产者线程会退出 |
演示代码
public static void test1() {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.element());
}
public static void test2() {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
System.out.println(blockingQueue.offer("d"));
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.peek());
}
public static void test3() {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
try {
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
blockingQueue.put("d");
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void test4() {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
try {
System.out.println(blockingQueue.offer("a", 1, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("b", 1, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("c", 1, TimeUnit.SECONDS));
System.out.println(blockingQueue.offer("d", 1, TimeUnit.SECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println(blockingQueue.poll(1, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(1, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(1, TimeUnit.SECONDS));
System.out.println(blockingQueue.poll(1, TimeUnit.SECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
}
}