三、采用BlockingQueue实现

BlockingQueue也是java.util.concurrent下的主要用来控制线程同步的工具。

BlockingQueue有四个具体的实现类,根据不同需求,选择不同的实现类
1、ArrayBlockingQueue:一个由数组支持的有界阻塞队列,规定大小的BlockingQueue,其构造函数必须带一个int参数来指明其大小.其所含的对象是以FIFO(先入先出)顺序排序的。

2、LinkedBlockingQueue:大小不定的BlockingQueue,若其构造函数带一个规定大小的参数,生成的BlockingQueue有大小限制,若不带大小参数,所生成的BlockingQueue的大小由Integer.MAX_VALUE来决定.其所含的对象是以FIFO(先入先出)顺序排序的。

3、PriorityBlockingQueue:类似于LinkedBlockQueue,但其所含对象的排序不是FIFO,而是依据对象的自然排序顺序或者是构造函数的Comparator决定的顺序。

4、SynchronousQueue:特殊的BlockingQueue,对其的操作必须是放和取交替完成的。

LinkedBlockingQueue 可以指定容量,也可以不指定,不指定的话,默认最大是Integer.MAX_VALUE,其中主要用到put和take方法,put方法在队列满的时候会阻塞直到有队列成员被消费,take方法在队列空的时候会阻塞,直到有队列成员被放进来。

import java.util.concurrent.BlockingQueue;  

public class Producer implements Runnable {
BlockingQueue<String> queue; public Producer(BlockingQueue<String> queue) {
this.queue = queue;
} @Override
public void run() {
try {
String temp = "A Product, 生产线程:"
+ Thread.currentThread().getName();
System.out.println("I have made a product:"
+ Thread.currentThread().getName());
queue.put(temp);//如果队列是满的话,会阻塞当前线程
} catch (InterruptedException e) {
e.printStackTrace();
}
} } import java.util.concurrent.BlockingQueue; public class Consumer implements Runnable{
BlockingQueue<String> queue; public Consumer(BlockingQueue<String> queue){
this.queue = queue;
} @Override
public void run() {
try {
String temp = queue.take();//如果队列为空,会阻塞当前线程
System.out.println(temp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; public class Test3 { public static void main(String[] args) {
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);
// BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
//不设置的话,LinkedBlockingQueue默认大小为Integer.MAX_VALUE // BlockingQueue<String> queue = new ArrayBlockingQueue<String>(2); Consumer consumer = new Consumer(queue);
Producer producer = new Producer(queue);
for (int i = 0; i < 5; i++) {
new Thread(producer, "Producer" + (i + 1)).start(); new Thread(consumer, "Consumer" + (i + 1)).start();
}
}
}

BlockingQueue接口,扩展了Queue接口

package java.util.concurrent;

import java.util.Collection;
import java.util.Queue; public interface BlockingQueue<E> extends Queue<E> {
boolean add(E e); boolean offer(E e); void put(E e) throws InterruptedException; boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException;
E take() throws InterruptedException; E poll(long timeout, TimeUnit unit)
throws InterruptedException; int remainingCapacity(); boolean remove(Object o); public boolean contains(Object o); int drainTo(Collection<? super E> c); int drainTo(Collection<? super E> c, int maxElements);
}

我们用到的take() 和put(E e)

两个方法,在ArrayBlockingQueue中的实现

  public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
final E[] items = this.items;
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == items.length)
notFull.await();
} catch (InterruptedException ie) {
notFull.signal(); // propagate to non-interrupted thread
throw ie;
}
insert(e);
} finally {
lock.unlock();
}
}
 private void insert(E x) {
items[putIndex] = x;
putIndex = inc(putIndex);
++count;
notEmpty.signal();
}
 public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == 0)
notEmpty.await();
} catch (InterruptedException ie) {
notEmpty.signal(); // propagate to non-interrupted thread
throw ie;
}
E x = extract();
return x;
} finally {
lock.unlock();
}
}
 private E extract() {
final E[] items = this.items;
E x = items[takeIndex];
items[takeIndex] = null;
takeIndex = inc(takeIndex);
--count;
notFull.signal();
return x;
}

看得到其实也是利用了Lock以及Condition条件变量的await()方法和signal()方法实现的,这个实现和我们之前实现的Lock用法区别:

1)使用了两个条件变量 consume的await放置在notEmpty 之上,唤醒在put的时候,produce的await放置在notfull之上,唤醒在take()的时候,唤醒是signal而不是signalAll,这样做就不会因为大量唤醒导致竞争从而减低效率,通过锁对象的分析,减低竞争

优点:更有利于协调生产消费线程的平衡

最新文章

  1. Python学习笔记(2) Python提取《釜山行》人物关系
  2. Microsoft Client Development MVP 2013 - 2014
  3. Idea安装及简单配置
  4. Mac必装app-持续更新
  5. [HTML]页面间传值的五种方法
  6. 第一次使用Git心得体会
  7. makefile懒人版(单个文件编译)
  8. angular中实现jQuery的Document Ready
  9. 吝啬的国度(dfs+vector)
  10. Jena文档《An Introduction to RDF and the Jena RDF API》的译文
  11. 单机千万级MQTT连接服务器测试报告
  12. Docker: 企业级镜像仓库Harbor部署(http)
  13. [06] Bean属性的注入
  14. Einbahnstrasse HDU2923
  15. 纯css竟可以做出边框这样长宽度的过渡效果
  16. [转]VS2015+OpenCV3.3 GPU模块和opencv_contrib模块的编译以及采用CMake编译opencv_contrib时提示“No extra modules found in folder”问题的解决方案
  17. 20145305 《网络对抗》注入Shellcode并执行&amp;Return-to-libc 攻击实验
  18. grunt入门讲解3:实例讲解使用 Gruntfile 配置任务
  19. Android studio 2.0--android增量更新的那些事
  20. Jvisualvm监控远程linux下Tomcat

热门文章

  1. Linux中如何批量删除目录下文件后缀
  2. 使用Keepalived实现Nginx高可用
  3. java线程中start和run的区别
  4. Opencv-python3.3版本安装
  5. 应用安全 - PHP - CMS - EmpireCMS - 漏洞 - 汇总
  6. Js 原型,原型链
  7. 布隆过滤器(Bloom Filter)原理以及应用
  8. CentOS7安装SVN1.9.12
  9. Ubuntu-虚拟机-忘记登陆密码
  10. .Net Core 3.0使用Grpc进行远程过程调用