Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

1. Introduction to BlockingQueue

BlockingQueue: BlockingQueue, FIFIO (first in, first out)

BlockingQueue provides thread-safe queue access: when a BlockingQueue is inserting data, if the queue is full, the thread will block and wait until the queue is full. When fetching data from a blocking queue, if the queue is empty, the thread will block and wait until the queue is empty.

In multithreaded environments, it is easy to share data through queues, such as in the classic “producer” and “consumer” model. Producers are the threads that add elements to the queue, and consumers are the threads that take elements from the queue.

2. BlockingQueue inheritance

BlockingQueue is an interface in the java.util.concurrent package that inherits Queue, which inherits Collection, as well as Set and List. BlockingQueue inheritance:

A Deque is a data structure with the properties of a queue and a stack. Elements in a two-ended queue can pop up from both ends, with restricted inserts and deletions occurring at both ends of the table.

LinkedBlockingQueue is an optional capacity blocking queue based on a linked list implementation. If no capacity is specified at initialization, the maximum value of int is used as the queue capacity by default. The element at the head of the queue is the oldest, and the element at the end of the queue is the latest. The new element will be inserted at the end of the queue.

The underlying ArrayBlockingQueue uses an array to implement the queue, and you need to specify the capacity when constructing the ArrayBlockingQueue, which means that once the underlying array is created, the capacity cannot be changed. So ArrayBlockingQueue is a volume-limited blocking queue. Therefore, enqueueing when the queue is full will block, as will enqueueing when the queue is empty.

BlockingQueue four groups of apis

1. Throw an exception

    public static void test1(a){
        // Create an array blocking queue of size 3
        ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue<>(3);
        // Add elements
        System.out.println(arrayBlockingQueue.add("a"));//true
        System.out.println(arrayBlockingQueue.add("b"));
        System.out.println(arrayBlockingQueue.add("c"));
// System.out.println(arrayBlockingQueue.add("d")); Queue Full is raised when adding failed

        System.out.println(arrayBlockingQueue.element());// Fetch the first element of the queue

        // Fetch the element
        System.out.println(arrayBlockingQueue.remove());
        System.out.println(arrayBlockingQueue.remove());
        System.out.println(arrayBlockingQueue.remove());
    }
Copy the code

2, do not throw exceptions, return values

public static void test2(a){
    // Create an array blocking queue of size 3
    ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue<>(3);
    // Add elements
    System.out.println(arrayBlockingQueue.offer("a"));//true
    System.out.println(arrayBlockingQueue.offer("b"));
    System.out.println(arrayBlockingQueue.offer("c"));
    System.out.println(arrayBlockingQueue.offer("d"));// Add failed, return false

    System.out.println(arrayBlockingQueue.peek());// Fetch the first element of the queue

    // Fetch the element
    System.out.println(arrayBlockingQueue.poll());
    System.out.println(arrayBlockingQueue.poll());
    System.out.println(arrayBlockingQueue.poll());
}
Copy the code

3. Keep waiting

    public static void test3(a) throws InterruptedException {
        // Create an array blocking queue of size 3
        ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue<>(3);
        // Add elements
        arrayBlockingQueue.put("a");//true
        arrayBlockingQueue.put("b");
        arrayBlockingQueue.put("c");
        arrayBlockingQueue.put("d");// Failed to add, the program will wait


        // Fetch the element
        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll());
    }
Copy the code

4, timeout wait

public static void test4(a) throws InterruptedException {
    // Create an array blocking queue of size 3
    ArrayBlockingQueue<Object> arrayBlockingQueue = new ArrayBlockingQueue<>(3);
    // Add elements
    System.out.println(arrayBlockingQueue.offer("a"));//true
    System.out.println(arrayBlockingQueue.offer("b"));
    System.out.println(arrayBlockingQueue.offer("c"));
    System.out.println(arrayBlockingQueue.offer("d".3, TimeUnit.SECONDS));// Wait 3 seconds, if add failed, return false, end of program

    System.out.println(arrayBlockingQueue.peek());// Fetch the first element of the queue

    // Fetch the element
    System.out.println(arrayBlockingQueue.poll());
    System.out.println(arrayBlockingQueue.poll());
    System.out.println(arrayBlockingQueue.poll());
    System.out.println(arrayBlockingQueue.poll(3, TimeUnit.SECONDS));// Wait for 3 seconds. If fetching fails, return null
}
Copy the code

Four sets of API summaries:

way An exception is thrown No exception thrown, return value Has been waiting for Timeout waiting for
add add() offer() put() offer(E e, long timeout, TimeUnit unit)
remove remove() poll() take() poll(long timeout, TimeUnit unit)
View the team leader element element() peek()