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)的更多相关文章

  1. Java多线程-新特征-阻塞队列ArrayBlockingQueue

    阻塞队列是Java5线程新特征中的内容,Java定义了阻塞队列的接口java.util.concurrent.BlockingQueue,阻塞队列的概念是,一个指定长度的队列,如果队列满了,添加新元素 ...

  2. 用Java如何设计一个阻塞队列,然后说说ArrayBlockingQueue和LinkedBlockingQueue

    前言 用Java如何设计一个阻塞队列,这个问题是在面滴滴的时候被问到的.当时确实没回答好,只是说了用个List,然后消费者再用个死循环一直去监控list的是否有值,有值的话就处理List里面的内容.回 ...

  3. Java中的阻塞队列-ArrayBlockingQueue(一)

    最近在看一些java基础的东西,看到了队列这章,打算对复习的一些知识点做一个笔记,也算是对自己思路的一个整理,本章先聊聊java中的阻塞队列 参考文章: http://ifeve.com/java-b ...

  4. Java并发编程:阻塞队列(转载)

    Java并发编程:阻塞队列 在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList), ...

  5. BlockingQueue阻塞队列(解决多线程中数据安全问题 可用于抢票,秒杀)

    案例:一个线程类中 private static BlockingQueue<Map<String, String>> dataQueue = new LinkedBlocki ...

  6. Java并发之BlockingQueue的使用

    Java并发之BlockingQueue的使用 一.简介 前段时间看到有些朋友在网上发了一道面试题,题目的大意就是:有两个线程A,B,  A线程每200ms就生成一个[0,100]之间的随机数, B线 ...

  7. 【转】Java并发编程:阻塞队列

    在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList),这些工具都为我们编写多线程程 ...

  8. 12、Java并发编程:阻塞队列

    Java并发编程:阻塞队列 在前面几篇文章中,我们讨论了同步容器(Hashtable.Vector),也讨论了并发容器(ConcurrentHashMap.CopyOnWriteArrayList), ...

  9. 【BlockingQueue】BlockingQueue 阻塞队列实现

    前言: 在新增的Concurrent包中,BlockingQueue很好的解决了多线程中,如何高效安全“传输”数据的问题.通过这些高效并且线程安全的队列类,为我们快速搭建高质量的多线程程序带来极大的便 ...

随机推荐

  1. webapi初学项目(增删改查)

    初学wenapi做了一个从数据库增删改查的项目 webapi: 1.创建项目:visual C# —> ASP.NET MVC 4 web应用程序 模板—>web api; 2.注册路由: ...

  2. 最小生成二叉树-prim算法

    1.prim算法:一种计算生成最小生成树的方法,它的每一步都会为一棵生长中的树添加一条边. 2.时间复杂度:

  3. MongoDB学习-在.NET中的简单操作

    1.新建MVC项目, 管理NuGet包,进入下载MongDB.net库文件 2.新增项目DAL数据访问层,引用以下库文件: 3.C# 访问MongoDB通用方法类: using MongoDB.Dri ...

  4. php中的字符串常用函数(五) explode 妙用

    // 示例 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh" ; list( $user , $pass , $uid , $gid , ...

  5. javax.el.PropertyNotFoundException: Property 'name' not found on type java.lang.String

    javax.el.PropertyNotFoundException: Property 'name' not found on type java.lang.String javax.el.Bean ...

  6. sql2012还原sql2008备份文件语句

    --sql2012还原sql2008语句 --选择master数据库,新建查询 输入下面sql语句 --选择兼容模式(sql 2008)创建数据库db RESTORE DATABASE db FROM ...

  7. AES .net 、JS 相互加密解密

    /// <summary> /// AES加密 /// </summary> public class AES { /// <summary> /// 加密 /// ...

  8. CSS3与页面布局学习笔记(二)——盒子模型(Box Model)、边距折叠、内联与块标签、CSSReset

    一.盒子模型(Box Model) 盒子模型也有人称为框模型,HTML中的多数元素都会在浏览器中生成一个矩形的区域,每个区域包含四个组成部分,从外向内依次是:外边距(Margin).边框(Border ...

  9. jQuery 浮动标签插件,帮助你提升表单用户体验

    浮动标签模式(Float Label Pattern)是最新流行的一种表单输入域的内容提示方式,当用户在输入框输入内容的时候,原先占位符的内容向上移动,显示在输入的内容的上面.这里推荐的这款 jQue ...

  10. 强大的JavaScript动画图形库mo.js

    最近在学习前端动画方面知识时发现了挺有趣的一个动画的图形库mo.js,页面效果真是酷炫,有兴趣的同学可以研究下:). 酷炫的效果: 以下是官方的demo效果,更多详情请查看 mo.js http:// ...