Java BlockingQueue Example(如何使用阻塞队列实现生产者-消费者问题)
Today we will look into Java BlockingQueue. java.util.concurrent.BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
Table of Contents [hide]
Java BlockingQueue

Java BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
Java BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.
Java BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue because it’s handled by implementation classes of BlockingQueue.
Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.
While implementing producer consumer problem in BlockingQueue, we will use ArrayBlockingQueue implementation. Following are some important methods you should know.
put(E e): This method is used to insert elements to the queue. If the queue is full, it waits for the space to be available.E take(): This method retrieves and remove the element from the head of the queue. If queue is empty it waits for the element to be available.
Let’s implement producer consumer problem using java BlockingQueue now.
Java BlockingQueue Example – Message
Just a normal java object that will be produced by Producer and added to the queue. You can also call it as payload or queue message.
Copy
package com.journaldev.concurrency;
public class Message {
private String msg;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Message</span><span class="hljs-params">(String str)</span></span>{
<span class="hljs-keyword">this</span>.msg=str;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getMsg</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> msg;
}
}
Java BlockingQueue Example – Producer
Producer class that will create messages and put it in the queue.
Copy
package com.journaldev.concurrency;
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
private BlockingQueue<Message> queue;
public Producer(BlockingQueue<Message> q){
this.queue=q;
}
@Override
public void run() {
//produce messages
for(int i=0; i<100; i++){
Message msg = new Message(""+i);
try {
Thread.sleep(i);
queue.put(msg);
System.out.println("Produced "+msg.getMsg());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//adding exit message
Message msg = new Message("exit");
try {
queue.put(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Java BlockingQueue Example – Consumer
Consumer class that will process on the messages from the queue and terminates when exit message is received.
Copy
package com.journaldev.concurrency;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable{
private BlockingQueue<Message> queue;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Consumer</span><span class="hljs-params">(BlockingQueue<Message> q)</span></span>{
<span class="hljs-keyword">this</span>.queue=q;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">try</span>{
Message msg;
<span class="hljs-comment">//consuming messages until exit message is received</span>
<span class="hljs-keyword">while</span>((msg = queue.take()).getMsg() !=<span class="hljs-string">"exit"</span>){
Thread.sleep(<span class="hljs-number">10</span>);
System.out.println(<span class="hljs-string">"Consumed "</span>+msg.getMsg());
}
}<span class="hljs-keyword">catch</span>(InterruptedException e) {
e.printStackTrace();
}
}
}
Java BlockingQueue Example – Service
Finally we have to create BlockingQueue service for producer and consumer. This producer consumer service will create the BlockingQueue with fixed size and share with both producers and consumers. This service will start producer and consumer threads and exit.
Copy
package com.journaldev.concurrency;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ProducerConsumerService {
public static void main(String[] args) {
//Creating BlockingQueue of size 10
BlockingQueue<Message> queue = new ArrayBlockingQueue<>(10);
Producer producer = new Producer(queue);
Consumer consumer = new Consumer(queue);
//starting producer to produce messages in queue
new Thread(producer).start();
//starting consumer to consume messages from queue
new Thread(consumer).start();
System.out.println("Producer and Consumer has been started");
}
}
Output of the above java BlockingQueue example program is shown below.
Copy
Producer and Consumer has been started
Produced 0
Produced 1
Produced 2
Produced 3
Produced 4
Consumed 0
Produced 5
Consumed 1
Produced 6
Produced 7
Consumed 2
Produced 8
...
Java Thread sleep is used in producer and consumer to produce and consume messages with some delay.
If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my articles directly. Recently I started creating video tutorials too, so do check out my videos on Youtube.
About Pankaj
Java BlockingQueue Example(如何使用阻塞队列实现生产者-消费者问题)的更多相关文章
- Java并发编程()阻塞队列和生产者-消费者模式
阻塞队列提供了可阻塞的put和take方法,以及支持定时的offer和poll方法.如果队列已经满了,那么put方法将阻塞直到有空间可用:如果队列为空,那么take方法将会阻塞直到有元素可用.队列可以 ...
- Java并发(基础知识)—— 阻塞队列和生产者消费者模式
1.阻塞队列 Blocki ...
- Java多线程—阻塞队列和生产者-消费者模式
阻塞队列支持生产者-消费者这种设计模式.该模式将“找出需要完成的工作”与“执行工作”这两个过程分离开来,并把工作项放入一个“待完成“列表中以便在随后处理,而不是找出后立即处理.生产者-消费者模式能简化 ...
- 基于阻塞队列的生产者消费者C#并发设计
这是从上文的<<图文并茂的生产者消费者应用实例demo>>整理总结出来的,具体就不说了,直接给出代码,注释我已经加了,原来的code请看<<.Net中的并行编程-7 ...
- java 用阻塞队列实现生产者消费者
package com.lb; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Blocking ...
- java多线程(8)---阻塞队列
阻塞队列 再写阻塞列队之前,我写了一篇有关queue集合相关博客,也主要是为这篇做铺垫的. 网址:[java提高]---queue集合 在这篇博客中我们接触的队列都是非阻塞队列,比如Priority ...
- 基于异步队列的生产者消费者C#并发设计
继上文<<基于阻塞队列的生产者消费者C#并发设计>>的并发队列版本的并发设计,原文code是基于<<.Net中的并行编程-4.实现高性能异步队列>>修改 ...
- java线程(7)——阻塞队列BlockingQueue
回顾: 阻塞队列,英文名叫BlockingQueue.首先他是一种队列,联系之前Java基础--集合中介绍的Queue与Collection,我们就很容易开始今天的阻塞队列的学习了.来看一下他们的接口 ...
- Python之路(第三十八篇) 并发编程:进程同步锁/互斥锁、信号量、事件、队列、生产者消费者模型
一.进程锁(同步锁/互斥锁) 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的, 而共享带来的是竞争,竞争带来的结果就是错乱,如何控制,就是加锁处理. 例 ...
随机推荐
- myeclipse中断点调试
在代码最左端,也就是行号位置处双击.会出现一个实心小圆点.即增加的断点.debug启动程序,就会运行到断点处: 按F5是进去方法里面. 按F6是一步一步走, 按F7是跳出方法里面(按F5后再按F7就跳 ...
- LightOJ 1070 Algebraic Problem (推导+矩阵高速幂)
题目链接:problem=1070">LightOJ 1070 Algebraic Problem 题意:已知a+b和ab的值求a^n+b^n.结果模2^64. 思路: 1.找递推式 ...
- Python 面向对象 —— super 的使用(Python 2.x vs Python 3.x)
注意区分当前的 Python 版本是 2.X 还是 3.X,Python 3.X 在 super 的使用上较之 Python 2.X 有较大的变化: 1. Python 2.x class Conta ...
- Elasticsearch之marvel(集群管理、监控)插件安装之后的浏览详解
前提 Elasticsearch之插件介绍及安装 https://i.cnblogs.com/posts?categoryid=950999&page=2 (强烈建议,从头开始看) 比如,我 ...
- 虚拟机中试用windows 8(视频)
虚拟机中试用windows 8(视频) VM7装windows 8基本没戏,建议用正式版vmware8.0,还有Oracle的Virtualbox 也没问题http://www.virtualbox. ...
- DM9000C网卡驱动
目的:通过学习,掌握如何移植.编写DM9000C网卡驱动 一.概述: DM9000是一款高度集成低功耗快速以太网处理器,该芯片集成了MAC和PHY.DM9000可以和CPU直接连接,支持8位.16位和 ...
- excel的隔行插入
https://wenda.so.com/q/1523455238213064 #公式 IF(ISODD(ROW()),OFFSET($B$1,INT((ROW(A1)-1)/2),),OFFSET( ...
- 用了Redis里面的map和set
map的操作用 hset,hget等 set的操作有 sadd sismember等 参考下面: http://blog.csdn.net/kwsy2008/article/details/48467 ...
- 数据存储值归档Archive
先比較一下各个数据存储之间的关系: 关于归档.是ios中的shu'j数据存储中的一种数据存储方式.以下了解一下归档中的一个实例: 以下的是父类person #import <Foundation ...
- Activity转换为View和把图片转换为View
package com.example.viewpager01; import java.util.ArrayList; import java.util.List; import android.a ...