博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java BlockingQueue示例
阅读量:2532 次
发布时间:2019-05-11

本文共 5999 字,大约阅读时间需要 19 分钟。

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.util.concurrent.BlockingQueue是一个Java队列,它支持以下操作:在检索和删除元素时等待队列变为非空,并在添加元素时等待队列中的空间变为可用。

Java BlockingQueue (Java BlockingQueue)

Java BlockingQueue doesn’t accept
null values and throw
NullPointerException if you try to store null value in the queue.

如果您尝试在队列中存储空值,则Java BlockingQueue不接受null值并抛出NullPointerException

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实现是线程安全的 。 所有排队方法本质上都是原子的,并使用内部锁或其他形式的并发控制。

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 BlockingQueue接口是Java集合框架的一部分,主要用于实现生产者使用者问题。 我们不必担心在BlockingQueue中等待生产者或对象对消费者可用的空间,因为它是由BlockingQueue的实现类处理的。

Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.

Java提供了几种BlockingQueue实现,例如ArrayBlockingQueueLinkedBlockingQueuePriorityBlockingQueueSynchronousQueue等。

While implementing producer consumer problem in BlockingQueue, we will use ArrayBlockingQueue implementation. Following are some important methods you should know.

在BlockingQueue中实现生产者使用者问题时,我们将使用ArrayBlockingQueue实现。 以下是一些您应该知道的重要方法。

  • 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.

    put(E e) :此方法用于将元素插入队列。 如果队列已满,它将等待空间可用。
  • 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.

    E take() :此方法从队列的开头检索并删除该元素。 如果队列为空,则等待元素可用。

Let’s implement producer consumer problem using java BlockingQueue now.

让我们现在使用java BlockingQueue实现生产者消费者问题。

Java BlockingQueue示例–消息 (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.

只是一个普通的Java对象,它将由Producer生成并添加到队列中。 您也可以将其称为有效负载或队列消息。

package com.journaldev.concurrency;public class Message {    private String msg;        public Message(String str){        this.msg=str;    }    public String getMsg() {        return msg;    }}

Java BlockingQueue示例–生产者 (Java BlockingQueue Example – Producer)

Producer class that will create messages and put it in the queue.

生产者类,它将创建消息并将其放入队列。

package com.journaldev.concurrency;import java.util.concurrent.BlockingQueue;public class Producer implements Runnable {    private BlockingQueue
queue; public Producer(BlockingQueue
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示例–使用者 (Java BlockingQueue Example – Consumer)

Consumer class that will process on the messages from the queue and terminates when exit message is received.

消费者类,它将处理来自队列的消息,并在收到退出消息时终止。

package com.journaldev.concurrency;import java.util.concurrent.BlockingQueue;public class Consumer implements Runnable{private BlockingQueue
queue; public Consumer(BlockingQueue
q){ this.queue=q; } @Override public void run() { try{ Message msg; //consuming messages until exit message is received while((msg = queue.take()).getMsg() !="exit"){ Thread.sleep(10); System.out.println("Consumed "+msg.getMsg()); } }catch(InterruptedException e) { e.printStackTrace(); } }}

Java BlockingQueue示例–服务 (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.

最后,我们必须为生产者和消费者创建BlockingQueue服务。 该生产者消费者服务将创建具有固定大小的BlockingQueue,并与生产者和消费者共享。 该服务将启动生产者和使用者线程并退出。

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
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.

上面的Java BlockingQueue示例程序的输出如下所示。

Producer and Consumer has been startedProduced 0Produced 1Produced 2Produced 3Produced 4Consumed 0Produced 5Consumed 1Produced 6Produced 7Consumed 2Produced 8...

is used in producer and consumer to produce and consume messages with some delay.

生产者和使用者中都使用来延迟产生和使用消息。

翻译自:

转载地址:http://ztlzd.baihongyu.com/

你可能感兴趣的文章
2016 - 1 -17 GCD学习总结
查看>>
linux安装php-redis扩展(转)
查看>>
Vue集成微信开发趟坑:公众号以及JSSDK相关
查看>>
技术分析淘宝的超卖宝贝
查看>>
i++和++1
查看>>
react.js
查看>>
P1313 计算系数
查看>>
NSString的长度比较方法(一)
查看>>
Azure云服务托管恶意软件
查看>>
My安卓知识6--关于把项目从androidstudio工程转成eclipse工程并导成jar包
查看>>
旧的起点(开园说明)
查看>>
生产订单“生产线别”带入生产入库单
查看>>
crontab导致磁盘空间满问题的解决
查看>>
java基础 第十一章(多态、抽象类、接口、包装类、String)
查看>>
Hadoop 服务器配置的副本数量 管不了客户端
查看>>
欧建新之死
查看>>
自定义滚动条
查看>>
APP开发手记01(app与web的困惑)
查看>>
笛卡尔遗传规划Cartesian Genetic Programming (CGP)简单理解(1)
查看>>
mysql 日期时间运算函数(转)
查看>>