Java并发之BlockingQueue 阻塞队列(ArrayBlockingQueue、LinkedBlockingQueue、DelayQueue、PriorityBlockingQueue、SynchronousQueue)
package com.thread.test.thread;
import java.util.Random;
import java.util.concurrent.*; /**
* Created by windwant on 2016/5/26.
*/
public class MyBlockingQueue {
public static void main(String[] args) throws InterruptedException {
testArrayBlockingQueue();
} /**
* 公平性 构造函数 true
*/
public static void testArrayBlockingQueue(){
BlockingQueue<String> abq = new ArrayBlockingQueue<String>(5);
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new MyPro(abq, 1000));
es.execute(new MyCus(abq, 5000));
es.shutdown();
} /**
* 基于链表节点的可设置容量的队列,先进先出,队尾插入元素,队首获取元素。
* 链表队列比基于数据的队列有更高的存取效率,但是在并发应用中效率无法预测。
*/
public static void testLinkedBlockingQueue(){
BlockingQueue<String> abq = new LinkedBlockingQueue<String>(5);
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new MyPro(abq, 20));
es.execute(new MyCus(abq, 2000));
es.shutdown();
} /**
* DelayQueue
* 无容量限制的阻塞队列,元素包含延迟时限,只有到达时限,元素才能被取出。
* 队列顶部是距离到期时间最远的元素。
* 如果所有的元素都未到期,将会返回null。
* 元素在执行getDelay()方法返回值小于等于0时过期,即使没有被通过take或者poll执行提取,它们也会被当作一般元素对待。
* 队列size方法返回所有元素的数量。
* 队列不能包含null元素。
*/
public static void testDelayQueue() throws InterruptedException {
DelayQueue<MyDelayItem> dq = new DelayQueue<MyDelayItem>();
ExecutorService es = Executors.newFixedThreadPool(5);
es.execute(new MyDelayPro(dq, 1000));
es.execute(new MyDelayCus(dq, 10000));
es.shutdown();
} /**
* 无容量限制的阻塞队列,元素顺序维持策略同PriorityQueue一样,支持阻塞获取
* 不允许添加null元素
* 元素必须支持排序
* 支持集合遍历,排序
*/
public static void testPriorityBlockingQueue() throws InterruptedException {
PriorityBlockingQueue<MyPriorityItem> pbq = new PriorityBlockingQueue<MyPriorityItem>();
ExecutorService es = Executors.newFixedThreadPool(5);
es.execute(new MyPriorityBlockingQueuePro(pbq, 1000));
es.execute(new MyPriorityBlockingQueueCus(pbq, 10000));
es.shutdown();
} /**
* 阻塞队列,插入元素和提取元素必须同步。
* 异步队列没有容量的概念。
* 无法使用peek,因为只有当你尝试移除时,元素才会存在。
* 无法插入元素,除非有另外一个线程同时尝试获取元素。
* 不支持遍历操作,因为队列中根本没有元素。
* 队列的顶部就是尝试插入元素的线程要插入的元素。
* 如果没有尝试插入元素的线程,那么就不存在能够提取的元素,poll会返回null。
* 集合操作contains返null
* 不允许插入null元素
* */
public static void testSynchronousQueue() throws InterruptedException {
SynchronousQueue<String> sq = new SynchronousQueue<String>();
ExecutorService es = Executors.newFixedThreadPool(5);
es.execute(new MySynchronousQueuePro(sq, 1000));
es.execute(new MySynchronousQueueCus(sq, 2000));
es.shutdown();
}
} /**
* 测试生产者
*/
class MyPro implements Runnable{ private BlockingQueue<String> bq; private int period = 1000; private Random r = new Random();
MyPro(BlockingQueue bq, int period){
this.bq = bq;
this.period = period;
} public void run() {
try{
while (true){
Thread.sleep(period);
String value = String.valueOf(r.nextInt(100));
if(bq.offer(value)){ //offer 能够插入就返回true,否则返回false
System.out.println("pro make value: " + value + " queue : " + bq.toString());
System.out.println("******************************************************");
}
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
} /**
* 测试消费者
*/
class MyCus implements Runnable{ private BlockingQueue<String> bq; private int period = 1000; private Random r = new Random();
MyCus(BlockingQueue bq, int period){
this.bq = bq;
this.period = period;
} public void run() {
try{
while (true){
Thread.sleep(period);
String value = bq.take(); //获取队列头部元素,无元素则阻塞
System.out.println("cus take value: " + value + " queue : " + bq.toString());
System.out.println("======================================================");
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
} /**
* 延迟队列元素 实现排序
*/
class MyDelayItem implements Delayed{ private long liveTime; private long removeTime; MyDelayItem(long liveTime, long removeTime){
this.liveTime = liveTime;
this.removeTime = TimeUnit.MILLISECONDS.convert(liveTime, TimeUnit.MILLISECONDS) + System.nanoTime();
} public long getDelay(TimeUnit unit) {
return unit.convert(removeTime - System.nanoTime(), unit);
} public int compareTo(Delayed o) {
if(o == null) return -1;
if(o == this) return 0;
if(o instanceof MyDelayItem){
MyDelayItem tmp = (MyDelayItem) o;
if(liveTime > tmp.liveTime){
return 1;
}else if(liveTime == tmp.liveTime){
return 0;
}else{
return -1;
}
}
long diff = getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
return diff > 0 ? 1 : diff == 0 ? 0 : -1;
} public String toString(){
return "{livetime: " + String.valueOf(liveTime) + ", removetime: " + String.valueOf(removeTime) + "}";
}
} /**
* 延迟队列测试生产者
*/
class MyDelayPro implements Runnable{ private DelayQueue<MyDelayItem> dq; private int period = 1000; private Random r = new Random(); MyDelayPro(DelayQueue dq, int period){
this.dq = dq;
this.period = period;
}
public void run() {
try{
while (true){
Thread.sleep(period);
if(dq.size() > 5){
continue;
}
MyDelayItem di = new MyDelayItem(r.nextInt(10), r.nextInt(10));
dq.offer(di);
System.out.println("delayqueue: add---" + di.toString() + "size: " + dq.size());
System.out.println("*************************************");
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
} /**
* 延迟队列测试消费者
*/
class MyDelayCus implements Runnable{ private DelayQueue<MyDelayItem> dq; private int period = 1000; MyDelayCus(DelayQueue dq, int period){
this.dq = dq;
this.period = period;
}
public void run() {
try{
while (true){
Thread.sleep(period);
MyDelayItem di = dq.take();
System.out.println("delayqueue: remove---" + di.toString());
System.out.println("delayqueue: ---" + dq.toString());
System.out.println("======================================");
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
} /**
* 延迟队列元素 时限排序对比延迟队列
*/
class MyPriorityItem implements Comparable<MyPriorityItem> { private int priority; MyPriorityItem(int priority){
this.priority = priority;
} /**
* 数字大优先级高
* @param o
* @return
*/
public int compareTo(MyPriorityItem o) {
if(o == null) return -1;
if(o == this) return 0;
if(priority > o.priority){
return -1;
}else if(priority == o.priority){
return 0;
}else{
return 1;
}
} public String toString(){
return "{priority: " + String.valueOf(priority) + "}";
}
} /**
* 优先队列测试生产者
*/
class MyPriorityBlockingQueuePro implements Runnable{ private PriorityBlockingQueue<MyPriorityItem> pbq; private int period = 1000; private Random r = new Random(); MyPriorityBlockingQueuePro(PriorityBlockingQueue pbq, int period){
this.pbq = pbq;
this.period = period;
}
public void run() {
try{
while (true){
Thread.sleep(period);
if(pbq.size() > 5){
continue;
}
MyPriorityItem pi = new MyPriorityItem(r.nextInt(10));
pbq.offer(pi);
System.out.println("PriorityBlockingQueue: add---" + pi.toString() + " size: " + pbq.size());
System.out.println("PriorityBlockingQueue: " + pbq.toString());
System.out.println("*************************************");
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
} /**
* 优先队列测试消费者
*/
class MyPriorityBlockingQueueCus implements Runnable{ private PriorityBlockingQueue<MyPriorityItem> pbq; private int period = 1000; private Random r = new Random(); MyPriorityBlockingQueueCus(PriorityBlockingQueue pbq, int period){
this.pbq = pbq;
this.period = period;
}
public void run() {
try{
while (true){
Thread.sleep(period);
MyPriorityItem di = pbq.take();
System.out.println("PriorityBlockingQueue: remove---" + di.toString());
System.out.println("PriorityBlockingQueue: ---" + pbq.toString());
System.out.println("======================================");
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
} /**
* 阻塞队列测试生产者
*/
class MySynchronousQueuePro implements Runnable{ private SynchronousQueue<String> sq; private int period = 1000; private Random r = new Random();
MySynchronousQueuePro(SynchronousQueue sq, int period){
this.sq = sq;
this.period = period;
} public void run() {
try{
while (true){
Thread.sleep(period);
String value = String.valueOf(r.nextInt(100));
if(sq.offer(value)) {
System.out.println("pro make value: " + value + " synchronous :" + sq.toString());
System.out.println("******************************************************");
}
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
} /**
* 阻塞队列测试消费者
*/
class MySynchronousQueueCus implements Runnable{ private BlockingQueue<String> sq; private int period = 1000; MySynchronousQueueCus(BlockingQueue sq, int period){
this.sq = sq;
this.period = period;
} public void run() {
try{
while (true){
Thread.sleep(period);
String value = sq.take();
System.out.println("cus take value: " + value + " synchronous :" + sq.toString());
System.out.println("======================================================");
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
项目地址:https://github.com/windwant/windwant-demo/tree/master/thread-demo
Java并发之BlockingQueue 阻塞队列(ArrayBlockingQueue、LinkedBlockingQueue、DelayQueue、PriorityBlockingQueue、SynchronousQueue)的更多相关文章
- Java多线程-新特征-阻塞队列ArrayBlockingQueue
阻塞队列是Java5线程新特征中的内容,Java定义了阻塞队列的接口java.util.concurrent.BlockingQueue,阻塞队列的概念是,一个指定长度的队列,如果队列满了,添加新元素 ...
- 用Java如何设计一个阻塞队列,然后说说ArrayBlockingQueue和LinkedBlockingQueue
前言 用Java如何设计一个阻塞队列,这个问题是在面滴滴的时候被问到的.当时确实没回答好,只是说了用个List,然后消费者再用个死循环一直去监控list的是否有值,有值的话就处理List里面的内容.回 ...
- Java中的阻塞队列-ArrayBlockingQueue(一)
最近在看一些java基础的东西,看到了队列这章,打算对复习的一些知识点做一个笔记,也算是对自己思路的一个整理,本章先聊聊java中的阻塞队列 参考文章: http://ifeve.com/java-b ...
- Java并发编程:阻塞队列(转载)
Java并发编程:阻塞队列 在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList), ...
- BlockingQueue阻塞队列(解决多线程中数据安全问题 可用于抢票,秒杀)
案例:一个线程类中 private static BlockingQueue<Map<String, String>> dataQueue = new LinkedBlocki ...
- Java并发之BlockingQueue的使用
Java并发之BlockingQueue的使用 一.简介 前段时间看到有些朋友在网上发了一道面试题,题目的大意就是:有两个线程A,B, A线程每200ms就生成一个[0,100]之间的随机数, B线 ...
- 【转】Java并发编程:阻塞队列
在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList),这些工具都为我们编写多线程程 ...
- 12、Java并发编程:阻塞队列
Java并发编程:阻塞队列 在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList), ...
- 【BlockingQueue】BlockingQueue 阻塞队列实现
前言: 在新增的Concurrent包中,BlockingQueue很好的解决了多线程中,如何高效安全“传输”数据的问题.通过这些高效并且线程安全的队列类,为我们快速搭建高质量的多线程程序带来极大的便 ...
随机推荐
- Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found.
在Eclipse中开发Android项目时,鼠标停放在想要查看帮助文档的类上面,发现没有显示帮助文档,显示了下面一句话: Note: This element neither has attached ...
- 实现在ios开发中的App滑动封面 UIScrollView
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. _scrol ...
- Mybatis批量添加对象List
1.对应的xml文件: <!--批量添加--><insert id="insertStandardItemInfo" parameterType="ha ...
- Java--关于计算表达式中赋值的细节问题
public class Test { public static void main(String[] args) { int t = 0; int p = 0; int q = 0; int ta ...
- 更新整理本人所有博文中提供的代码与工具(Java,2013.10)
为了更方便地管理博文中涉及的各种代码与工具资源,现在把这些资源迁移到 Google Code 中,有兴趣者可前往下载. Java 1.<高效 Java Web 应用开发框架 JessMA v3. ...
- python数据类型详解及列表字典集合推导式详解
一.运算符 Python语言支持以下类型的运算符: 算术运算符 如: #!/usr/bin/env python # -*- coding:utf-8 -*- a = 5 b = 6 print(a ...
- Java Swing快速构建窗体应用程序
以前接触java感觉其在桌面开发上,总是不太方便,没有一个好的拖拽界面布局工具,可以快速构建窗体. 最近学习了一下NetBeans IDE 8.1,感觉其窗体设计工具还是很不错的 , 就尝试一下做了一 ...
- 高性能javascript学习笔记系列(3) -DOM编程
参考 高性能javascript 文档对象模型(DOM)是独立于语言的,用于操作XML和HTML文档的程序接口API,在浏览器中主要通过DOM提供的API与HTML进行交互,浏览器通常会把DOM和ja ...
- JavaScript的运动框架学习总结
一.目录 1. 入门案例——实现匀速运动 2. 入门案例——实现缓冲运动 3. 实现任意值的运动框架v.1 4. 改进任意值的运动框架v.2 5. 改进任意值的运动框架v.3 6. 实现链式运动框架 ...
- [deviceone开发]-课程表的例子
一.简介 这个例子是根据一个真实app的一个页面的需求来实现的demo,通过动态add ui的方式,动态bind数据构建一个完整的课程表示例.示例并不完善,但是可以给大家一个启发. 二.效果图 三.相 ...