Java集合学习笔记之队列系列一:基于LinkedBlockingQueue实现阻塞队列

60 阅读1分钟
import java.util.NoSuchElementException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Example {
    public static void main(String[] Args) {
        BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<>(2);
        // 添加数据,查看offer、add连个方法的添加效果
        System.out.println(blockingQueue.offer("offer添加元素")); // true
        System.out.println(blockingQueue.add("add添加元素")); // true
        try {
            blockingQueue.add("队列满了,会曝出异常");
        }catch (IllegalStateException e){
            System.out.println(e.getMessage()); // Queue full
        }
        System.out.println(blockingQueue.offer("队列满了,返回false")); // false


        // 查看并删除数据
        System.out.println(blockingQueue.remove()); // offer添加元素
        System.out.println(blockingQueue.poll()); // add添加元素

        try{
            blockingQueue.remove();
        }catch (NoSuchElementException e){
            System.out.println(e.getMessage()); // null
        }

        System.out.println(blockingQueue.poll()); // null

        // 查看且不删除数据
        System.out.println(blockingQueue.offer("offer添加元素")); // true
        System.out.println(blockingQueue.add("add添加元素")); // true
        System.out.println(blockingQueue.element()); // offer添加元素
        System.out.println(blockingQueue.peek()); // offer添加元素
        // 清空队列
        blockingQueue.clear();
        System.out.println(blockingQueue.peek()); // 返回null
        try{
            blockingQueue.element();
        }catch (NoSuchElementException e){
            System.out.println(e.getMessage()); // null
        }
    }

}