1.加入元素,包含三种方式 put add offer
put 加入元素的时候如果队列已满则会阻塞等待
final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
for (int i = 0; i < 3; i++) {
System.out.println("add "+i);
try {
queue.put(i + "");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("over...");
add 0
add 1
add 2
add加入元素的时候如果队列已满则会抛出异常
final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
for (int i = 0; i < 3; i++) {
System.out.println("add "+i);
queue.add(i + "");
}
System.out.println("over...");
add 0
add 1
add 2
Exception in thread "main" java.lang.IllegalStateException: Queue full
at java.util.AbstractQueue.add(AbstractQueue.java:98)
at testqueue.test.main(test.java:50)
offer加入元素的时候如果队列已满则会返回false
final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
for (int i = 0; i < 3; i++) {
System.out.println("add "+i);
System.out.println(queue.offer(i + ""));;
}
System.out.println("over...");
add 0
true
add 1
true
add 2
false
over...
2.去除元素,包含三种方式take remove poll
take 如果队列为空则会阻塞等待
final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
System.out.println("waiting for take 。。。");
try {
System.out.println("remove " + queue.take());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("take over。。。");
waiting for take 。。。
remove 如果队列为空则会抛出异常
final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
System.out.println("waiting for remove 。。。");
System.out.println("remove " + queue.remove());
System.out.println("remove over。。。");
waiting for remove 。。。
Exception in thread "main" java.util.NoSuchElementException
at java.util.AbstractQueue.remove(AbstractQueue.java:117)
at testqueue.test.main(test.java:49)
poll 如果队列为空会返回null
final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
System.out.println("waiting for poll 。。。");
System.out.println("remove " + queue.poll());
System.out.println("poll over。。。");
waiting for poll 。。。
remove null
poll over。。。