BlockingQueue原理
這個BlockingQueue是個接口,BlockingQueue 通常用於一個線程生產對象,而另外一個線程消費這些對象的場景。下圖是對這個原理的闡述:
用於生產者消費者模型,那就是多個線程可以操作生產,多個線程可以操作消費,如果生產過快大於隊列的長度的話,會不讓它生產了,讓它阻塞。消費過快,也是同樣的道理。
BlockingQueue的方法
但是由於應用的方法不同,你也可以不使用阻塞的那種方式,
\ | 拋異常 | 待定值 | 阻塞 | 超時 |
---|---|---|---|---|
插入 | add(o) | offer(o) | put(o) | offer(o,timeout,timeunit) |
移除 | remove(o) | poll(o) | take(o) | poll(o,timeout,timeunit) |
檢查 | element(o) | peek(o) |
四組不同的行爲方式解釋:
拋異常:如果試圖的操作無法立即執行,拋一個異常。
特定值:如果試圖的操作無法立即執行,返回一個特定的值(常常是 true / false)。
阻塞:如果試圖的操作無法立即執行,該方法調用將會發生阻塞,直到能夠執行。
超時:如果試圖的操作無法立即執行,該方法調用將會發生阻塞,直到能夠執行,但等待時間不會超過給定值。返回一個特定值以告知該操作是否成功(典型的是 true / false)。
BlockingQueue的實現
● ArrayBlockingQueue
● DelayQueue
● LinkedBlockingQueue
● PriorityBlockingQueue
● SynchronousQueue
Demo
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Main1 {
public static void main(String[] args) {
BlockingQueue<Integer> bq = new ArrayBlockingQueue<Integer>(1024);
Producer producer = new Producer(bq);
Consumer consumer = new Consumer(bq);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
t1.start();
t2.start();
}
}
class Producer implements Runnable {
private BlockingQueue<Integer> blockingQueue = null;
public Producer() {
}
public Producer(BlockingQueue<Integer> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
try {
Thread.sleep(1000);
blockingQueue.put(1);
Thread.sleep(1000);
blockingQueue.put(4);
Thread.sleep(1000);
blockingQueue.put(555);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
private BlockingQueue<Integer> blockingQueue = null;
public Consumer() {
}
public Consumer(BlockingQueue<Integer> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
try {
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
結果
在運行的過程中,明顯有阻塞的過程。如果將sleep()的時間設置的更長一些,這個阻塞的效果會更加明顯。