-
remove方法,队列为空时,继续移除元素抛出异常
public class BlockingQueueTest {
public static void main(String[] args) {
test1();
}
public static void test1(){
BlockingQueue blockingQueue = new ArrayBlockingQueue(3);
System.out.println(blockingQueue.add(1));
System.out.println(blockingQueue.add(2));
System.out.println(blockingQueue.add(3));
System.out.println("=====================================");
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
}
}
上面只添加了3个元素,下面移除4个元素。当移除第4个元素时,抛出异常

-
offer和poll方法,有返回值,不抛出异常
public class BlockingQueueTest {
public static void main(String[] args) {
test2();
}
public static void test2(){
BlockingQueue blockingQueue = new ArrayBlockingQueue(3);
System.out.println(blockingQueue.offer(1));
System.out.println(blockingQueue.offer(2));
System.out.println(blockingQueue.offer(3));
System.out.println(blockingQueue.offer(4));
System.out.println("=====================================");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
}
}
执行结果

-
返回队首元素
blockingQueue.element();
blockingQueue.peek()
-
put方法,队列满时阻塞,直到队列有空位为止
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
test3();
}
public static void test3() throws InterruptedException {
BlockingQueue blockingQueue = new ArrayBlockingQueue(3);
blockingQueue.put(1);
blockingQueue.put(2);
blockingQueue.put(3);
blockingQueue.put(4);
}
}
-
task方法,队列为空时阻塞,直到队列有元素为止
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
test3();
}
public static void test3() throws InterruptedException {
BlockingQueue blockingQueue = new ArrayBlockingQueue(3);
blockingQueue.put(1);
blockingQueue.put(2);
blockingQueue.put(3);
System.out.println("======================");
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
}
}
-
超时等待
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
test4();
}
public static void test4() throws InterruptedException {
BlockingQueue blockingQueue = new ArrayBlockingQueue(3);
System.out.println(blockingQueue.offer(1));
System.out.println(blockingQueue.offer(2));
System.out.println(blockingQueue.offer(3));
System.out.println(blockingQueue.offer(4, 2, TimeUnit.SECONDS));
System.out.println("======================");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll(2,TimeUnit.SECONDS));
}
}
-
总结上面4组API
方法 |
抛出异常 |
不抛异常,返回值 |
阻塞 |
超时阻塞 |
添加 |
add |
offer |
put |
offer(obj,v,t) |
移除 |
remove |
poll |
task |
poll(v,t) |
查看队首 |
element |
peek |
— |
— |