目錄
阻塞隊列
阻塞隊列(BlockingQueue)相較於普通的隊列,添加了2個附加的操作。
(1)在隊列爲空時,獲取元素的線程會等待隊列變爲非空。
(2)當隊列滿時,存儲元素的線程會等待隊列可用。
阻塞隊列常用於生產者和消費者的場景,生產者是往隊列裏添加元素的線程,消費者是從隊列裏拿元素的線程。
如果是非阻塞隊列在實現生產者和消費者模型時,我們需要手動的添加同步策略以及線程之間的喚醒策略。所以,阻塞隊列可以很好解決這一問題。
代碼實現:
public class Test {
private int queueSize = 10;
private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(queueSize);
public static void main(String[] args) {
Test test = new Test();
Producer producer = test.new Producer();
Consumer consumer = test.new Consumer();
producer.start();
consumer.start();
}
class Consumer extends Thread{
@Override
public void run() {
consume();
}
private void consume() {
while(true){
try {
queue.take();
System.out.println("從隊列取走一個元素,隊列剩餘"+queue.size()+"個元素");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer extends Thread{
@Override
public void run() {
produce();
}
private void produce() {
while(true){
try {
queue.put(1);
System.out.println("向隊列取中插入一個元素,隊列剩餘空間:"+(queueSize-queue.size()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
博客參考
http://ifeve.com/java-blocking-queue/
http://www.cnblogs.com/dolphin0520/p/3932906.html