BlockingQueue (blocking queue)

BlockingQueue is an interface that inherits from the Queue interface, and the Queue interface inherits from Collection; the commonly used implementation classes of the BlockingQueue interface are ArrayBlockingQueue (based on an array) and LinkedBlockingQueue (based on a linked list). The four commonly used APIs of BlockingQueue are:

1. 操作队列失败时会抛出异常
add(入队/添加,当队列满的时候抛出异常)
remove(出队/删除,当队列空的时候抛出异常)
element(查看队首元素,当队列空的时候抛出异常)

2. 操作队列失败的时候不会抛出异常
offer(入队/添加,当队列满的时候返回false)
poll(出队/删除,当队列空的时候返回null)
peek(查看队首元素,当队列空的时候返回null)

3. 操作队列失败的时候会阻塞,一直到可以操作为止(无限等待)
take(入队/添加,当队列满的时候阻塞等待)
put(出队/删除,当队列空的时候阻塞等待)

4. 操作队列失败的时候会阻塞一段时间,时间到则停止等待(限时等待)
入队:offer方法的重载,可以指定等待的时间,例如offer(1,5, TimeUnit.SECONDS);表示队列满的时候会阻塞5秒
出队:poll方法的重载,可以指定等待的时间,例如poll(1,5, TimeUnit.SECONDS);表示队列空的时候会阻塞5秒

BlockingQueue blocking queue implements producer and consumer models

Reference article: https://www.cnblogs.com/expiator/articles/9317929.html

/**
 * @Author Baker.chen
 * @create 2020/9/13 14:39
 *
 * 使用阻塞队列BlockingQueue实现生产者和消费者模式
 */
public class Main4 {
    
    
    public static void main(String[] args) throws Exception{
    
    
        LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
        // 使用线程池创建线程,为了方便,直接使用Executors工具类为我们提供好的线程池
        // 实际开发中,应该避免使用这种方式,而应该自己去定义一个线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();
        threadPool.execute(new Producer(queue));
        threadPool.execute(new Consumer(queue));
    }
}
// 生产者
class Producer implements Runnable{
    
    
    private BlockingQueue queue;
    public Producer(BlockingQueue queue) {
    
    
        this.queue = queue;
    }
    @Override
    public void run() {
    
    
        for (int i = 0; i < 10; i++) {
    
    
            try {
    
    
                System.out.println("生产者生产中……");
                queue.put(i);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

// 消费者
class Consumer implements Runnable{
    
    
    private BlockingQueue queue;
    public Consumer(BlockingQueue queue) {
    
    
        this.queue = queue;
    }
    @Override
    public void run() {
    
    
        while (true) {
    
    
            try {
    
    
                System.out.println("消费者消费中……");
                System.out.println(queue.take());
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

From the above code, we can know that due to the blocking queue characteristics of BlockingQueue, operation failure will cause blocking waiting. Therefore, it is easier to use BlockingQueue to implement the producer and consumer model than using the traditional wait/notify method to implement the producer consumer model!

Guess you like

Origin blog.csdn.net/can_chen/article/details/108686115