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. "Hello World!" for the NetBeans IDE

    "Hello World!" for the NetBeans IDE It's time to write your first application! These detai ...

  2. 点击一个div隐藏另一个div

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  3. 使用attrs.xml自定义属性

    控件有很多属性,如android:id.android:layout_width.android:layout_height等,但是这些属性都是系统自带的属性.使用attrs.xml文件,可以自己定义 ...

  4. Docker: adding a file from a parent directory

    17down votefavorite 4 In my Dockerfile I've got : ADD ../../myapp.war /opt/tomcat7/webapps/ That fil ...

  5. 面试问题整理笔记系列 一 Java容器类

                                               虚线框表示接口:实线框表示实体类:粗线框表示最常用的实体类:虚线箭头表示实现了这个接口:实现箭头表示类可以制造箭头 ...

  6. CGI与Servlet的比较

    转自:http://www.maxhis.info/java/cgi-vs-servlet/ 谢! 概括来说,CGI和Servlet可以完成相同的功能. 一:CGI(Common Gateway In ...

  7. android 去掉标题

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FUL ...

  8. servlet同一用户不同页面共享数据

    如何实现不同页面之间的数据传递,实现页面的数据共享?常见的方法有以下4种: 1)表单提交(form) 2)sendRedirect()跳转 3)session技术 4)Cookie技术 表单提交 这是 ...

  9. bootbox.js

    bootbox:一个弹出框插件,官网看一下例子就好了:http://bootboxjs.com/examples.html 目前来说应该只要调用bootbox.js就可以了,没有css的问题 1.有最 ...

  10. fontIconPicker – 优雅的 jQuery 字体图标选择

    jQuery fontIconPicker 是一个小的 jQuery 插件,它可以让你实现一个优雅的带有分类.搜索和分页功能的图标选择器.图标列表可手动从下拉列表框,图标数组或对象,或者从 Fonte ...