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之路(第三十八篇) 并发编程:进程同步锁/互斥锁、信号量、事件、队列、生产者消费者模型
一.进程锁(同步锁/互斥锁) 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的, 而共享带来的是竞争,竞争带来的结果就是错乱,如何控制,就是加锁处理. 例 ...
随机推荐
- codeforces 543 C Remembering Strings
题意:若一个字符串集合里的每一个字符串都至少有一个字符满足在i位上,仅仅有它有,那么这个就是合法的,给出全部串的每一个字符修改的花费,求变成合法的最小代价. 做法:dp[i][j].前i个串的状态为j ...
- 63.note.js之 Mongodb在Nodejs上的配置及session会话机制的实现
转自:https://www.cnblogs.com/alvin_xp/p/4751784.html 1.第一步安装mongodb数据库,这直接官网下载,这里不介绍. 2.也可以使用npm实现直接下载 ...
- iOS-APP-Icon 图标启动图及名字的设置
本文讲下appIcon图标.启动图及名字的设置 icon for iOS 图标大小参照苹果官网:https://developer.apple.com/library/ios/qa/qa1686/_i ...
- 在英语中,in,on,at的用法是?
在几点:at xx:xx ,在那月: in Dec./Jan.……, 在那日:on Thur./Mon.……,on Jan. 16th 时间前面 at, 年月日前面如果有具体的日子,就是具体的哪一天 ...
- Linear Decoders
Sparse Autoencoder Recap In the sparse autoencoder, we had 3 layers of neurons: an input layer, a hi ...
- Font-Awesome最新版完整使用教程
何为Font-Awesome Font Awesome gives you scalable vector icons that can instantly be customized - size, ...
- js配合My97datepicker给日期添加天数
<input name="ctl00$ContentPlaceHolder1$txtTimeStart" type="text" value=" ...
- FineUI 页面跳转
要加 EnableAjax=false; <f:Button ID="btn1" EnableAjax="false" OnClick="btn ...
- node 内存溢出
遇到这个问题的人可以更快解决 再复制写一篇 利于百度搜索 坑爹的node 内存溢出 react开发项目 安装一个插件依赖 ,然后就报错了 报错如下(自己的没有截图出来 这是从别人的截图---报错基本 ...
- Echarts Y轴min显示奇葩问题(做此记录)
项目需求是根据不同情况显示最大值最小值 有9-35 12-50 9-50 三种情况 前面两种可以显示出来 但是9-50的话 最小值9显示不出来 8,7等就可以显示出来 后面想到强制从最小值 ...