阻塞队列
ArrayBlockingQueue
package main.java.com.allen.study;
import java.util.concurrent.ArrayBlockingQueue;
/**
* @program: spring
* @description: ${description}
* @packagename: main.java.com.allen.study
* @author: Allen-wang
* @date: 2020-04-27 21:17
**/
public class ArrayBlockingQueueDemo {
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue(10);
{
init();
}
public void init(){
new Thread(()->{
while (true){
try {
String data = abq.take();
System.out.println("receive:" + data);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}).start();
}
public void addData(String data) throws InterruptedException {
abq.add(data);
System.out.println("send:" + data);
Thread.sleep(1000);
}
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueueDemo arrayBlockingQueueDemo = new ArrayBlockingQueueDemo();
for(int i=0;i<1000;i++) {
arrayBlockingQueueDemo.addData("data"+ i);
}
}
}
LinkedBlockingQueue
操作方法:
插入元素
add():添加元素到队列,满了会报错
offer(超时时间):添加元素到队列,成功会返回true。超时时间是元素满了之后会阻塞这段时间。超时就退出。
put():满了之后一直阻塞,直到可用。
删除元素:
remove():删除
poll():取元素,为空返回null
take():拿不到会阻塞