Blocking queue ArrayBlockingQueue implements producer consumer model

Blocking queue diagram: 

        The difference between a blocking queue and a normal queue is that when the queue is empty, the operation of getting elements from the queue will be blocked, or when the queue is full, the operation of adding elements to the queue will be blocked. Threads trying to get elements from the empty blocking queue will be blocked until other threads insert new elements into the empty queue. Similarly, threads trying to add new elements to a full blocking queue will also be blocked until other threads make the queue free again.

        There are several blocking queues. This article only uses one of the two most commonly used blocking queues: ArrayBlockingQueue.

        ArrayBlockingQueue: A blocking queue based on an array implementation. The capacity must be specified when creating an ArrayBlockingQueue object. And you can specify fairness and unfairness, which is unfair by default.

 

       The blocking queue scenario just conforms to the producer-consumer model in the operating system. In the traditional producer-consumer problem, wait() and signal() operations must be implemented in a specific position. The order cannot be reversed, which is more cumbersome. The java.util.concurrent package introduced by jdk 5.0 obviously simplifies the producer-consumer problem very well, and it is all done automatically. Wait() and signal() do not need to be written, which is great.

put(): used to store elements to the end of the queue, if the queue is full, wait;

take(): used to take elements from the head of the team, if the queue is empty, wait;

 

       Code description:

       The thread is implemented by inheriting the Thread class and rewriting the run method.

        Math.Random() generates a random floating-point number from 0 to 1 (not including 0 and 1). After expanding by 10 times +1, the result is a random integer from 1 to 10, so that each product produced by the producer is put into the blocking queue After the end of the queue (or the consumer takes a product from the head of the blocking queue), the corresponding thread will sleep for 1 to 10ms

import java.util.concurrent.ArrayBlockingQueue;

public class Test {
    private int queueSize = 10;//初始化阻塞队列长度为10
    private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(queueSize);

    public static void main(String[] args)  {
        Test test = new Test();
        Producer producer = test.new Producer();
        Consumer consumer = test.new Consumer();

        producer.start();
        consumer.start();
    }

    class Consumer extends Thread{

        @Override   //此注解用于检测是否重写了父类的run方法,如果下行的run单词写错编译器就会报红
        public void run() {
            consume();
        }

        private void consume() {
            int ran;//随机生成数1-10放在ran中
            while(true){
                try {
                    ran=(int)Math.random()*10+1;//产生1-10的随机数
                    queue.take();
                    System.out.println("从队列取走一个元素,队列剩余"+queue.size()+"个元素");
                    sleep(ran);//线程休眠产生的随机时间ran
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class Producer extends Thread{
        @Override   
        public void run() {
            produce();
        }
        private void produce() {
            int ran;
            while(true){
                try {
                    ran=(int)Math.random()*10+1;
                    queue.put(1);
                    System.out.println("向队列插入一个元素,队列剩余空间:"+(queueSize-queue.size()));
                    sleep(ran);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

If you run it, you will find that the program will not hang and not run, which confirms that the blocking queue is thread-safe, that is, there will be no producer blocking while consumer blocking.

Guess you like

Origin blog.csdn.net/Zhongtongyi/article/details/105962443