1、阻塞队列(BlockingDeque)
首先我们来认识一下什么是堵塞队列
阻塞队列即实现了线程安全和阻塞的队列。在队列为空时,获取元素的线程会等待队列存放元素变为非空;在队列满时,存放元素的线程会等待队列取出元素变为不满。
阻塞队列常应用于生产者-消费者模型
我们常用的阻塞队列主要有两类
LinkedBlockingDeque
ArrayBlockingQueue
使用LinkedBlockingDeque
BlockingDeque<Integer> blockingDeque = new LinkedBlockingDeque<>();使用ArrayBlockingQueue
ArrayBlockingQueue<String> blockingDeque = new ArrayBlockingQueue<>(100);
//100表示队列容量2、阻塞队列中常用的方法
常用的方法有三个:put(),take(),peek()
put()
put()方法用于在阻塞队列中存放元素
blockingDeque.put(1);take()
take()方法用于获取并取出队首元素
System.out.println(blockingDeque.take());peek()
peek()用于获取队首元素
System.out.println(blockingDeque.peek());3、用阻塞队列实现生产者-消费者模型
这里我们用LinkedBlockingDeque类
我们用两个线程分别来给阻塞队列添加/取出元素,以此来实现生产者/消费者模型
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
public class demo1 {
    public static void main(String[] args) throws InterruptedException {
        BlockingDeque<Integer> blockingDeque = new LinkedBlockingDeque<>();
        Thread thread1 = new Thread(()->{
            int n = 0;
            while (true){
                try {
                    blockingDeque.put(n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("生产元素"+n);
                n++;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread thread2 = new Thread(()->{
            while (true){
                try {
                    System.out.println("消费元素"+blockingDeque.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}
运行结果

注意:上面代码中,我们在生产者线程里使用了sleep()休眠,以此来控制生产消费的速度



















