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. Objective-C(十九、通知-消息发送模式之中的一个)——iOS开发基础

    结合之前的学习笔记以及參考<Objective-C编程全解(第三版)>,对Objective-C知识点进行梳理总结. 知识点一直在变.仅仅是作为參考.以苹果官方文档为准~ 十九.通知-消息 ...

  2. OpenCASCADE中散乱Edge生成Wire

    OpenCASCADE中散乱Edge生成Wire eryar@163.com Abstract. In OpenCASCADE a wire can be built from any number ...

  3. hq-源码编译

    这里编译整个项目的基本格式是 ./mk + 平台名 +项目名_客户名 +mmm +new 例如 ./mk hq6735_65c_b1k_l1 al811_doov mmm new 编译单个模块 ./m ...

  4. js -- img 随着鼠标滚轮的变化变化

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

  5. spring源码分析之@Conditional

    根源在AnnotationConfigApplicationContext和AnnotationConfigWebApplicationContext,以AnnotationConfigApplica ...

  6. Postman APP

    http://chromecj.com/web-development/2017-12/870.html    Postman 工具模拟http各种协议请求.

  7. DG的数据保护模式

    DG的数据保护模式 数据保护膜有三种: – Maximum protection – Maximum availability – Maximum performance Maximum protec ...

  8. iframe自适应高度解决方法 .

    <div id="leftBar"> <iframe name="tag" src="_iframe.html" styl ...

  9. 【习题 8-8 UVA - 1612】Guess

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] double千万不要用==判断相等... 而且两个保留2位有效数字的数字x,y 判断它们相等应该这样. int temp1 = ro ...

  10. HDU 2191 悼念512汶川大地震

    悼念512汶川大地震遇难同胞——珍惜现在,感恩生活 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Jav ...