java.util.concurrent 包里的 BlockingQueue 接口表示一个线程放入和提取实例的队列
阻塞队列(BlockingQueue)是一个支持两个附加操作的队列。这两个附加的操作支持阻塞的插入和移除方法
1)支持阻塞的插入方法:意思是当队列满时,队列会阻塞插入元素的线程,直到队列不满。
2)支持阻塞的移除方法:意思是在队列为空时,获取元素的线程会等待队列变为非空
BlockingQueue 通常用于一个线程生产对象,而另外一个线程消费这些对象的场景。下图是对这个原理的阐述:
一个线程往里边放,另外一个线程从里边取的一个 BlockingQueue。
BlockingQueue 具有 4 组不同的方法用于插入、移除以及对队列中的元素进行检查。如果请求的操作不能得到立即执行的话,每个方法的表现也不同。这些方法如下:
抛异常 | 特定值 | 阻塞 | 超时 | |
---|---|---|---|---|
插入 | add(o) | offer(o) | put(o) | offer(o, timeout, timeunit) |
移除 | remove(o) | poll(o) | take(o) | poll(timeout, timeunit) |
检查 | element(o) | peek(o) |
四组不同的行为方式解释:
同过一个简单的生产消费模型,可以看出效果。当队列里的存放到达最大容量是,生产者会阻塞着,得消费者取走消息。容器里面有新的空间后,继续存放。效果复制以下代码,执行main方法就行
public class Consumer implements Runnable {
private BlockingQueue MQlist = null;
public Consumer(BlockingQueue MQlist) {
this.MQlist = MQlist;
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(500);
String name = Thread.currentThread().getName();
String take = MQlist.take();
System.out.println("消费者"+name+"获取了"+take);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Producer implements Runnable {
private BlockingQueue MQlist = null;
public Producer(BlockingQueue MQlist) {
this.MQlist = MQlist;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(500);
String name = Thread.currentThread().getName();
MQlist.put(name + ":" + i);
System.out.println("生产者"+name+"存放了"+i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Demo {
public static void main(String[] args) {
BlockingQueue bq=new ArrayBlockingQueue(5);
//producer是一个线程任务类,执行的方法是往队列里放10条数据
Producer producer=new Producer(bq);
//consumer是线程任务类,执行方法是往队列里拿数据 他两的队列是同一个队列,
Consumer consumer=new Consumer(bq);
new Thread(producer).start();
new Thread(consumer).start();
new Thread(producer).start();
new Thread(consumer).start();
new Thread(producer).start();
}
}
生产者会一直放下去,最后是consumer在消费
public class Demo {
public static void main(String[] args) {
BlockingQueue bq=new LinkedBlockingQueue(5);
//producer是一个线程任务类,执行的方法是往队列里放10条数据
Producer producer=new Producer(bq);
//consumer是线程任务类,执行方法是往队列里拿数据 他两的队列是同一个队列,
Consumer consumer=new Consumer(bq);
new Thread(producer).start();
new Thread(consumer).start();
new Thread(producer).start();
new Thread(consumer).start();
new Thread(producer).start();
}
}
带优先级的无界阻塞队列,每次出队都返回优先级最高的元素,是二叉树最小堆的实现,研究过数组方式存放最小堆节点的都知道,直接遍历队列元素是无序的。该实现类需要自己实现一个继承了 Comparator 接口的类, 在插入资源时会按照自定义的排序规则来对资源数组进行排序。
package com.blockingqueue.PriorityBlockingQueue;
/**
* @Author zongx
* @Date 2020/6/5 17:16
* @Version 1.0
*/
public class Person implements Comparable {
int age;
String name;
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Person o) {
return this.age - o.age;
}
}
package com.blockingqueue.PriorityBlockingQueue;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
/**
* @Author zongx
* @Date 2020/6/5 16:00
* @Version 1.0
*/
public class Producer implements Runnable {
private BlockingQueue MQlist = null;
public Producer(BlockingQueue MQlist) {
this.MQlist = MQlist;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(500);
String name = Thread.currentThread().getName();
double random = Math.random();
int j = (int) (i*random*10);
Person person = new Person(j, name);
MQlist.put(person);
System.out.println("生产者"+name+"存放了"+i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.blockingqueue.PriorityBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* @Author zongx
* @Date 2020/6/5 16:04
* @Version 1.0
*/
public class Consumer implements Runnable {
private BlockingQueue MQlist = null;
public Consumer(BlockingQueue MQlist) {
this.MQlist = MQlist;
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(2000);
String name = Thread.currentThread().getName();
Person take = MQlist.take();
System.out.println("消费者"+name+"获取了"+take);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.blockingqueue.PriorityBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
/**
* @Author zongx
* @Date 2020/6/5 16:07
* @Version 1.0
*/
public class Demo {
public static void main(String[] args) {
BlockingQueue bq=new PriorityBlockingQueue(5);
//producer是一个线程任务类,执行的方法是往队列里放10条数据
Producer producer=new Producer(bq);
//consumer是线程任务类,执行方法是往队列里拿数据 他两的队列是同一个队列,
Consumer consumer=new Consumer(bq);
new Thread(producer).start();
new Thread(producer).start();
new Thread(consumer).start();
}
}
DelayQueue是一个无界阻塞队列,只有在延迟期满时才能从中提取元素。该队列的头部是延迟期满后保存时间最长的Delayed 元素。为了具有调用行为,存放到DelayDeque的元素必须继承Delayed接口。Delayed接口使对象成为延迟对象,它使存放在DelayQueue类中的对象具有了激活日期。该接口强制执行下列两个方法。
做任务调度:离到期时间越近,越早,当时间等于0调用
package com.blockingqueue.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
* @Author zongx
* @Date 2020/6/5 17:46
* @Version 1.0
*/
public class Duty implements Delayed {
private String name;
private long expireTime;
//定义时间工具类
private TimeUnit timeUnit = TimeUnit.SECONDS;
@Override
public long getDelay(TimeUnit unit) {
return expireTime - System.currentTimeMillis();
}
@Override
public int compareTo(Delayed o) {
if (this.getDelay(timeUnit) - o.getDelay(timeUnit) > 0){
return 1;
}else if (this.getDelay(timeUnit) - o.getDelay(timeUnit) < 0){
return -1;
}else {
return 0;
}
}
public Duty(String name, long expireTime) {
this.name = name;
this.expireTime = expireTime;
}
@Override
public String toString() {
return "Duty{" +
"name='" + name + '\'' +
", expireTime=" + (expireTime-1591351020000l) +
'}';
}
}
package com.blockingqueue.DelayQueue;
import com.blockingqueue.PriorityBlockingQueue.Person;
import java.util.concurrent.BlockingQueue;
/**
* @Author zongx
* @Date 2020/6/5 16:00
* @Version 1.0
*/
public class Producer implements Runnable {
private BlockingQueue MQlist = null;
public Producer(BlockingQueue MQlist) {
this.MQlist = MQlist;
}
@Override
public void run() {
try {
for (int i = 0; i < 3; i++) {
Thread.sleep(500);
String name = Thread.currentThread().getName();
double random = Math.random();
long j = (long) (i*random*1000) + System.currentTimeMillis();
Duty person = new Duty( name,j);
MQlist.put(person);
System.out.println("生产者"+name+"存放了"+(int) (i*random*1000));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.blockingqueue.DelayQueue;
import com.blockingqueue.PriorityBlockingQueue.Person;
import java.util.concurrent.BlockingQueue;
/**
* @Author zongx
* @Date 2020/6/5 16:04
* @Version 1.0
*/
public class Consumer implements Runnable {
private BlockingQueue MQlist = null;
public Consumer(BlockingQueue MQlist) {
this.MQlist = MQlist;
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(2000);
String name = Thread.currentThread().getName();
Duty take = (Duty) MQlist.take();
System.out.println("消费者"+name+"获取了"+take);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.blockingqueue.DelayQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.PriorityBlockingQueue;
/**
* @Author zongx
* @Date 2020/6/5 16:07
* @Version 1.0
*/
public class Demo {
public static void main(String[] args) {
BlockingQueue bq=new DelayQueue();
//producer是一个线程任务类,执行的方法是往队列里放10条数据
Producer producer=new Producer(bq);
//consumer是线程任务类,执行方法是往队列里拿数据 他两的队列是同一个队列,
Consumer consumer=new Consumer(bq);
new Thread(producer).start();
new Thread(producer).start();
new Thread(consumer).start();
}
}
应用场景:
特点:
/**
* 不像ArrayBlockingQueue、LinkedBlockingDeque之类的阻塞队列依赖AQS实现并发操作,
* SynchronousQueue直接使用CAS实现线程的安全访问。它是个没有容量的队列,
*/
public static void main(String[] args) throws Exception {
final BlockingQueue bq=new SynchronousQueue<>();
//第一种情况 这种直接添加,会出异常Queue full
//bq.add("steve");
//第二种情况 如果有线程先取,会阻塞着,这样就能放进去
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println( bq.take());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(1000);
//可以理解为交接给了等待的线程,不是真正的存放进去了
bq.put("stevetao");
}