<br />
<br />
<br />java的线程池的工作队列用到了并发队列。<br />队列一般用在生产者消费者的场景中,处理需要排队的需求。<br />
<br />
<br />你好,我是李福春,今天的问题是:<br />
<br />ConcurrentLinkedQueue和LinkedBlockingQueue有什么区别?<br />
<br />
<br />答:都是java提供的并发安全队列,都提供了等待性的操作,take,put 区别如下:<br />
并发队列类层级
<br />层级图如下:<br />
<br />
生产者消费者例子
package org.example.mianshi.queue;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.stream.IntStream;
/**
* 作者: carter
* 创建日期: 2020/3/30 17:39
* 描述: 生产者消费者例子
*/
public class ConsumerProduceApp {
public static void main(String[] args) {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(1000);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
producer.start();
consumer.start();
try {
producer.join();
consumer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static class Consumer extends Thread {
private BlockingQueue<String> blockingQueue;
public Consumer(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
String msg = "";
do {
try {
msg = blockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(msg);
} while (!Objects.equals(msg, "quit"));
}
}
public static class Producer extends Thread {
private BlockingQueue<String> blockingQueue;
public Producer(BlockingQueue<String> blockingQueue) {
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
IntStream.rangeClosed(1, 100)
.forEach(i -> {
try {
blockingQueue.put("msg" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
try {
blockingQueue.put("quit");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
<br />
<br />有界队列:<br />
<br />ArrayBlockingQueue: 容量固定,内存连续队列<br />
<br />LinkedBlockingQueue : 设置大小为有界队列,不设置则为无界队列<br />
<br />SychronousQueue: 容量为0, take,put操作互相等待<br />
<br />
<br />无界队列:<br />
<br />PriorityQueue: 优先级无界队列<br />
<br />DelayedQueue: 延迟无界队列<br />
队列的选择
<br />
<br />按照是否有界: 一般选择ArrayBlockingQueue , LinkedBlockingQueue <br />
<br />按照内存紧密性: ArrayBlockingQueue
按照吞吐量:LinkedBlockingQueue
线程接力或者队列信息较少的高性能: SynchronouseQueue<br />
<br />
小结
<br />本节机会大了ConcurrentBlockingQueue和LinkedBlockingQueue的区别,然后回顾了java提供的队列层级。<br />
<br />通过一个简单的生产者消费者例子展示了队列的基本使用。<br />
<br />最后介绍了不同场景下队列的选择。<br />
<br />
<br />
原创不易,转载请注明出处。