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

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

    
    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.

  • 相关阅读:
    遍历数组的常用方法
    ios 提审被拒4.3,更换账号提审处理
    js 判断手机有没有网络
    js网页拉起支付宝支付
    uni-app常用 HTML5+APP 设置
    uni-app 无痛刷新 token 方法
    uni-app通过判断接口403跳转登录页面的问题
    APICloud项目纪要
    Vue递归组件实现层层嵌套显示数据
    Git恢复删除的分支
  • 原文地址:https://www.cnblogs.com/jpfss/p/9373293.html
Copyright © 2020-2023  润新知