Pratice Of Concurrency(一: BlockingQueue )

Java java.util.currencypackage BlockingQueueinterface means that thread can add and extract objects in a queue. In the following paragraphs, we will learn how to use the BlockingQueueinterface.

BlockingQueue use

BlockingQueue typical application is the production of objects for a thread, another thread consumer.

The following is a schematic description of FIG:

A blocking queue accompanied by a thread to add objects to a queue, another thread to extract objects from the queue.

Production concurrent thread is responsible for the production of new objects added to it in the queue until it reaches the boundary value queue can hold. That is at capacity limit. If the queue reaches capacity limit, blocking the production of thread will happen when you insert a new object. Until a consumer thread until the object is removed from the queue.

Consumer thread is responsible for removing objects from blocking the queue and process them. If you try to remove the empty queue consumer thread from an empty queue, the thread will block until the consumer thread production to put up a queue object.

BlockingQueue method

A blocking queue contains four distinct set of methods for performing inserted in the queue, and check the element is removed. It differs in that each set of a different behavior of the operation request can not be executed immediately following these methods list:

Throws Exception Special Value Blocks Times Out
Insert add(o) offer(o) put(o) offer(o, timeout, time unit)
Remove remove(o) poll() take() poll(timeout, timeunit)
Examine element() peek()

Four different combination of the following behaviors:

  1. Throws Exception: When attempting operation can not be executed immediately, will throw an exception
  2. Special Value: when try operation can not be executed immediately, to specify a return value (usually true / false)
  3. Blocks: When attempting operation can not be executed immediately, call blocking method capable of performing up until success
  4. Time Out: When attempting operation can not be executed immediately, blocking method calls until you can execute it succeeds, but the long wait should not exceed a specified timeout period if exceeded, regardless of success or failure to return a specified value (a typical example of this is true.. / false)

Can not be inserted nullinto the BlockingQueue in. If you do that, BlockingQueue will throw a NullPointerException.

Of course, we are also able to access all the elements BlockingQueue, not just the team head and the tail. For example, you need a team for the implementation of an object, but it decided to cancel your application. So you can still use a similar remove (o) method remove the queue specified object. However, this is not very efficient, so you should not use such methods unless you really need to do so.

The realization of a variety of BlockingQueue

BlockingQueue just an interface, so you need to use one of its many implemented to use it. java.util.concurrencyPackage there are several BlockingQueue interface (in Java6):

  • ArrayBlockingQueue
  • DelayQueue
  • LinkedBlockingQueue
  • PriorityBlockingQueue
  • SynchronousQueue

Java BlockingQueue examples

The following is an example of the Java BlockingQueue. BlockingQueue example class that implements the interface, ArrayBlockingQueue.

First, BlockingQueueExample classes start of production and consumption are a thread. Thread is responsible for the production string is inserted into a shared BlockingQueue, whereas the consumer thread is responsible for the removal of them.

public class ArrayBlockingQueueExample {
    public static void main(String[] args) {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(1024);
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        new Thread(producer).start();
        new Thread(consumer).start();

        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码

Here is the Producer category. Note that we once put every call () will allow the thread to sleep for one second. This causes a blockage occurs when the consumer thread waits objects in the queue.

public class Producer implements Runnable {
    private ArrayBlockingQueue<String> queue;

    public Producer(ArrayBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            queue.put("1");
            Thread.sleep(1000);
            queue.put("2");
            Thread.sleep(1000);
            queue.put("3");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码

The following is a Consumer class. It is only responsible for the string removed from the queue and printed out by the System.out.

package org.menfre;

import java.util.concurrent.ArrayBlockingQueue;

public class Consumer implements  Runnable {
    private ArrayBlockingQueue<String> queue;

    public Consumer(ArrayBlockingQueue<String> queue){
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            System.out.println(queue.take());
            System.out.println(queue.take());
            System.out.println(queue.take());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码

This blog series for the product after we review or understand basic written translation, from the original review written by Jakob Jenkov Java.util.concurrent

Next: ArrayBlockingQueue

Guess you like

Origin juejin.im/post/5cf548aef265da1bb2771b0d