标签:print lang usequeue image 大小 priority closed for blocking
层级图如下:
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();
}
}
}
}
按照吞吐量:LinkedBlockingQueue
线程接力或者队列信息较少的高性能: SynchronouseQueue
本节机会大了ConcurrentBlockingQueue和LinkedBlockingQueue的区别,然后回顾了java提供的队列层级。
通过一个简单的生产者消费者例子展示了队列的基本使用。
最后介绍了不同场景下队列的选择。
原创不易,转载请注明出处。
标签:print lang usequeue image 大小 priority closed for blocking
原文地址:https://www.cnblogs.com/snidget/p/12600362.html