1、阻塞队列的概述
当队列是空的,从队列中获取元素的操作将会被阻塞;
当队列是满的,从队列中添加元素的操作将会被阻塞;
试图从空的队列中获取元素的线程将会被阻塞,直到其他线程往空的队列插入新的元素;
试图向已满的队列中添加新元素的线程将会被阻塞,直到其他线程从队列中移除一个或多个元素或者完全清空,使队列变得空闲起来并后续新增。
2、阻塞队列架构架构
3、阻赛队列的方法
4、阻赛队列演示
package com.example.block_queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* 阻塞队列
*/
public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
//创建阻塞队列
BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
//---------------------------第一组------------------------------------------
//添加数据
/* System.out.println(queue.add("a"));
System.out.println(queue.add("b"));
System.out.println(queue.add("c"));
//System.out.println(queue.add("d"));
//检测
//System.out.println(queue.element());
//取出数据
System.out.println(queue.remove());
System.out.println(queue.remove());
System.out.println(queue.remove());
System.out.println(queue.remove());*/
//---------------------------第二组------------------------------------------
//添加数据
/* System.out.println(queue.offer("a"));
System.out.println(queue.offer("b"));
System.out.println(queue.offer("c"));
System.out.println(queue.offer("hello"));
//取出数据
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());*/
//---------------------------第三组------------------------------------------
//放数据
/* queue.put("a");
queue.put("b");
queue.put("c");
//queue.put("d");
//取数据
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());*/
//---------------------------第四组------------------------------------------
queue.offer("a");
queue.offer("b");
queue.offer("c");
queue.offer("d",3, TimeUnit.SECONDS);
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll(3,TimeUnit.SECONDS));
}
}