LinkedBlockingQueue和ConcurrentLinkedQueue的区别

来源:互联网 发布:时时彩平刷软件破解版 编辑:程序博客网 时间:2024/05/16 09:05

LinkedBlockingQueue是一个链表阻塞队列;

初始化:

  • new LinkedBlockingQueue(); 默认初始化size为Integer.MAX_VALUE
  • new LinkedBlockingQueue(size); size不能设置为0,为0会抛出 java.lang.ExceptionInInitializerError异常

方法介绍:

添加方法 -> 当队列填充满了后,下面方法不同的效果:

  • add(target),会抛出java.lang.IllegalStateException: Queue full;
  • put(target), 会进入阻塞状态,直到有空间可以插入;
  • offer(target), 会返回true(添加成功),false(添加失败);
  • offer(target,timeout, TimeUnit.HOURS), 会在超时时间范围内一直尝试添加(成功返回true),如果超过超时时间范围还未添加成功,则返回false;

消费方法 -> 当队列中没有数据时,下面方法不同的效果:

  • element(), 会抛出java.util.NoSuchElementException;
  • take(), 会进入阻塞状态,直到有有数据可以取出;
  • poll(), 会返回null;
  • poll(timeout, TimeUnit.HOURS),会在超时时间范围内,一直尝试取出数据;如果超过超时时间范围还没有数据则返回null;
  • peek(), 返回第一个元素,不删除;上面的消费后都会删除原来的元素;

消费者,生产者代码:

public class LinkedBlockingQueueTest {    private static LinkedBlockingQueue<Apple> linkedBlockingQueue = new LinkedBlockingQueue();    static class Apple{        String model;        public Apple(String model){            this.model = model;        }        @Override        public String toString() {            return "Apple{" + "model='" + model + '\'' + '}';        }    }    public static void main(String[] args) throws Exception {        new LinkedBlockingQueueTest().production(new Apple("iphone4"));        new LinkedBlockingQueueTest().production(new Apple("iphone4s"));        new LinkedBlockingQueueTest().production(new Apple("iphone5"));        new LinkedBlockingQueueTest().production(new Apple("iphone6"));        new LinkedBlockingQueueTest().production(new Apple("iphone6plus"));        Thread.sleep(3000);        System.out.println(linkedBlockingQueue.toString());        new LinkedBlockingQueueTest().consumption();        new LinkedBlockingQueueTest().consumption();        new LinkedBlockingQueueTest().consumption();        new LinkedBlockingQueueTest().consumption();        new LinkedBlockingQueueTest().consumption();    }    //保证插入队列和输出插入信息同步    private static synchronized void put(Apple apple){        try {            linkedBlockingQueue.put(apple);            System.out.println("生产一个苹果" + apple);        } catch (Exception e) {            e.printStackTrace();        }    }    //保证取出队列和输出取出信息同步    private static synchronized void take() {        try {            Apple apple = linkedBlockingQueue.take();            System.out.println("消费一个苹果" + apple);        } catch (Exception e) {            e.printStackTrace();        }    }    //生产方法    private void production(Apple apple){        new Thread(()->{            put(apple);        }).start();    }    //消费方法    private void consumption(){        new Thread(()->{            take();        }).start();    }}

ConcurrentLinkedQueue只有LinkedBlockingQueue中的一些非阻塞方法,如add,offer, element, poll;

  • 区别:ConcurrentLinkedQueue的size方法需要遍历队列效率低;
    LinkedBlockingQueue有一个值直接记录size;
阅读全文
0 0