阻塞队列——四组API

方式 抛出异常 有返回值,不抛出异常 阻塞等待 超时等待
添加 add() offer() put() offer(…)
移除 remove() poll() take() poll(…)
检测队首元素 element() peek()

第一组

1、添加抛出异常

public class Demo01 {
    public static void main(String[] args) {
        // 构造方法参数:public ArrayBlockingQueue(int capacity, boolean fair)
        // 第一个参数:初始化阻塞队列的容量大小
        // 第二个参数:指定该阻塞队列是否为公平或不公平锁

        BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);

        // 添加元素
        queue.add("a");
        queue.add("b");
        queue.add("c");
    }
}

运行结果:

2、移除抛出异常

public class Demo01 {
    public static void main(String[] args) {
        // 构造方法参数:public ArrayBlockingQueue(int capacity, boolean fair)
        // 第一个参数:初始化阻塞队列的容量大小
        // 第二个参数:指定该阻塞队列是否为公平或不公平锁

        BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);

        // 添加元素
        System.out.println(queue.add("a"));
        System.out.println(queue.add("b"));

        // 移除元素
        queue.remove();
        queue.remove();
        queue.remove();
    }
}

运行结果:

第二组

1、添加有返回值

package com.lzp.blockqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @Author LZP
 * @Date 2020/8/8 8:12
 * @Version 1.0
 *
 * 有返回值,且不抛出异常
 */
public class Demo02 {
    public static void main(String[] args) {
        // 创建阻塞队列对象
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);

        // 添加元素:若添加成功,则返回true,反之,则返回false
        System.out.println(queue.offer(1));
        System.out.println(queue.offer(2));
        System.out.println(queue.offer(3));
        System.out.println(queue.offer(4));
    }
}

运行结果:

2、移除有返回值

package com.lzp.blockqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @Author LZP
 * @Date 2020/8/8 8:12
 * @Version 1.0
 *
 * 有返回值,且不抛出异常
 */
public class Demo02 {
    public static void main(String[] args) {
        // 创建阻塞队列对象
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);

        // 添加元素:若添加成功,则返回true,反之,则返回false
        System.out.println(queue.offer(1));
        System.out.println(queue.offer(2));
        System.out.println(queue.offer(3));
        System.out.println(queue.offer(4));

        // 移除元素:若移除成功,则返回移除的值,反之,则返回false
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }
}

运行结果: