Java Concurrent Programming Tool JUC Part 2: ArrayBlockingQueue

The class ArrayBlockingQueueis BlockingQueuethe implementation class of the interface, it is a bounded blocking queue, and an array is used internally to store the queue elements . "Bounded" here means that there is an upper limit on the storage capacity, and elements cannot be stored infinitely. There is an upper limit of storage capacity at the same time. This upper limit is specified at the time of initial instantiation and cannot be modified afterwards.

ArrayBlockingQueueFIFO (First In, First Out) method is adopted internally to realize the access of queue data. The element at the head of the queue is the element object with the longest storage time in the queue, and the element at the end of the queue is the shortest storage time in the queue. Element object.

The following code shows how to initialize one ArrayBlockingQueueand add an object to it:

BlockingQueue queue = new ArrayBlockingQueue(1024);
queue.put("1");   //向队列中添加元素
Object object = queue.take();   //从队列中取出元素

BlockingQueueGenerics can be used to limit the type of data stored in the queue. The following code uses String as the generic, which means that the queue can only store String types.

BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1024);
queue.put("1");
String string = queue.take();

Realize an instance of production and consumption

In the previous article, we have talked about: BlockingQueue is often used to produce and consume buffer queues. Below we will use it ArrayBlockingQueueto truly realize an example of production and consumption.

The class BlockingQueueExampleopens two independent threads, one is the Producerproducer thread, which is responsible for adding data to the queue; the other is the Consumerconsumer thread, which is responsible for removing data from the queue for processing.

public class BlockingQueueExample {

    public static void main(String[] args) throws Exception {
        //使用ArrayBlockingQueue初始化一个BlockingQueue,指定容量的上限为1024
        BlockingQueue queue = new ArrayBlockingQueue(1024);

        Producer producer = new Producer(queue);  //生产者
        Consumer consumer = new Consumer(queue);  //消费者

        new Thread(producer).start();  //开启生产者线程
        new Thread(consumer).start();  //开启消费者线程

        Thread.sleep(4000);
    }
}

The class Produceris a producer, and put()an object is put into the queue using a method every 10 seconds , and put into it three times. In this 10-second interval, the consumer thread will be blocked after the queue data is taken away by the consumer.

public class Producer implements Runnable{

    protected BlockingQueue queue = null;

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            queue.put("1");
            Thread.sleep(10000);
            queue.put("2");
            Thread.sleep(10000);
            queue.put("3");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The following code is a consumer class Consumer, which gets the element object to be processed from the queue and calls System.outto print it out.

public class Consumer implements Runnable{

    protected BlockingQueue queue = null;

    public Consumer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            System.out.println(queue.take());
            System.out.println(queue.take());
            System.out.println(queue.take());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The above code prints the result is printed once every 10 seconds, because take()the method is no element to be taken when the consumer will block the current thread, so they are in a wait state in the queue, this method we introduced in the previous section BlockingQueueof It has already been explained at that time.

Welcome to follow my blog, there are many boutique collections

  • This article is reproduced indicate the source (en must not turn only the text): letters Gebo off .

If you think it is helpful to you, please like and share it for me! Your support is my inexhaustible creative motivation! . In addition, the author has output the following high-quality content recently, and I look forward to your attention.

Guess you like

Origin blog.csdn.net/hanxiaotongtong/article/details/115107810