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.

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&lt;Message&gt; 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.


About Pankaj

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.

Java BlockingQueue Example(如何使用阻塞队列实现生产者-消费者问题)的更多相关文章

  1. Java并发编程()阻塞队列和生产者-消费者模式

    阻塞队列提供了可阻塞的put和take方法,以及支持定时的offer和poll方法.如果队列已经满了,那么put方法将阻塞直到有空间可用:如果队列为空,那么take方法将会阻塞直到有元素可用.队列可以 ...

  2. Java并发(基础知识)—— 阻塞队列和生产者消费者模式

    1.阻塞队列                                                                                        Blocki ...

  3. Java多线程—阻塞队列和生产者-消费者模式

    阻塞队列支持生产者-消费者这种设计模式.该模式将“找出需要完成的工作”与“执行工作”这两个过程分离开来,并把工作项放入一个“待完成“列表中以便在随后处理,而不是找出后立即处理.生产者-消费者模式能简化 ...

  4. 基于阻塞队列的生产者消费者C#并发设计

    这是从上文的<<图文并茂的生产者消费者应用实例demo>>整理总结出来的,具体就不说了,直接给出代码,注释我已经加了,原来的code请看<<.Net中的并行编程-7 ...

  5. java 用阻塞队列实现生产者消费者

    package com.lb; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Blocking ...

  6. java多线程(8)---阻塞队列

    阻塞队列 再写阻塞列队之前,我写了一篇有关queue集合相关博客,也主要是为这篇做铺垫的. 网址:[java提高]---queue集合  在这篇博客中我们接触的队列都是非阻塞队列,比如Priority ...

  7. 基于异步队列的生产者消费者C#并发设计

    继上文<<基于阻塞队列的生产者消费者C#并发设计>>的并发队列版本的并发设计,原文code是基于<<.Net中的并行编程-4.实现高性能异步队列>>修改 ...

  8. java线程(7)——阻塞队列BlockingQueue

    回顾: 阻塞队列,英文名叫BlockingQueue.首先他是一种队列,联系之前Java基础--集合中介绍的Queue与Collection,我们就很容易开始今天的阻塞队列的学习了.来看一下他们的接口 ...

  9. Python之路(第三十八篇) 并发编程:进程同步锁/互斥锁、信号量、事件、队列、生产者消费者模型

    一.进程锁(同步锁/互斥锁) 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的, 而共享带来的是竞争,竞争带来的结果就是错乱,如何控制,就是加锁处理. 例 ...

随机推荐

  1. LinkedIn Cubert 实践指南

    · LinkedIn Cubert安装指南 · Understanding Cubert Concepts(一)Partitioned Blocks · Understanding Cubert Co ...

  2. asp.net 站点在Apache下的配置,就这么简单

    asp.net 站点在Apache下的配置,就这么简单 # # Virtual Hosts # # If you want to maintain multiple domains/hostnames ...

  3. js关于循环的理解

    学习任何语言都离不开循环,js也是一样,看了网上的资料,整理一份关于js循环的理解. 1.最基础循环,js和其他高级语言一样使用for.while循环 (function() { for(var i= ...

  4. vue+mui+html5+ plus开发的混合应用底部导航的显示与隐藏

    1. 模板相关内容(template) <template> <div> <transition :name="transitionName"> ...

  5. 今日题解------codeforce 893d

    题意:给你一个数列,小于零表示表示信用卡里取出钱,大于零表示信用卡里存钱,等于零表示要查询信用卡, 如果被查到信用卡里的钱小于零,那你就GG,或者在任何时候你的信用卡里的钱大于d的话(不需要找ai等于 ...

  6. C#之用户自定义控件

    一.新建用户自定义控件 如下图所示,想通过LED的点击来实现亮和灭使用去控制下位机. LED亮: LED灭: 首先新建一个用户控件类,如下图所示步骤: 在资源中,添加现有文件中加入图片 加入的图片可以 ...

  7. VPS搭建与IPv6使用教程

    VPS搭建与IPv6使用教程 SoftEther命令: yum -y install gcc zlib-devel openssl-devel readline-devel ncurses-devel ...

  8. lubuntu自动登录(lxde)

    lubuntu自动登录(lxde) 1.重启ubuntu,在grub界面长按shirft进入grub菜单: 2.选择recovery mode,按"e"键进入编辑页面: 3.把ro ...

  9. Qt之输出控制

    简述 在Qt项目开发过程中,往往需要对程序的一些信息进行控制,比如:打印日志.调试信息等,便于我们后期查找.跟踪及定位问题. 下面,我们来分享下常用的几种方式. 简述 示例代码 应用程序输出 控制台输 ...

  10. modal模态框插件

    用法: <!--模态框--> <div class="modal fade" id="myModal"> <div class=& ...