The use of Java thread queue - ArrayBlockingQueue

ArrayBlockingQueue

ArrayBlockingQueue is an array-based bounded blocking queue. It needs to specify the capacity when it is created, and you can choose whether to require fairness. If the fair parameter is set to true, threads will access the queue in FIFO order; otherwise, the access order is undefined.

ArrayBlockingQueue can be used to implement a fixed-size buffer. For example, the following code creates an ArrayBlockingQueue with a capacity of 5 and adds 10 elements to it. It can be seen that when the queue is full, the insert operation will be blocked until there is a free position.

import java.util.concurrent.ArrayBlockingQueue;

public class ArrayBlockingQueueDemo {
    public static void main(String[] args) {
        // 创建一个容量为5的数组阻塞队列
        ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(5);
        // 向队列中添加10个元素
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("Trying to put " + i + " into queue");
                abq.put(i);
                System.out.println("Successfully put " + i + " into queue");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Output result (partial):

Trying to put 0 into queue
Successfully put 0 into queue
Trying to put 1 into queue
Successfully put 1 into queue
Trying to put 2 into queue
Successfully put 2 into queue
Trying to put 3 into queue
Successfully put 3 into queue
Trying to put 4 into queue
Successfully put 4 into queue
Trying to put 5 into queue
// 此时队列已满,插入操作被阻塞,直到有其他线程从队列中获取元素

Supongo que te gusta

Origin blog.csdn.net/caicai250/article/details/131441419
Recomendado
Clasificación