zoukankan      html  css  js  c++  java
  • LinkedBlockingQueue 与ConcurrentLinkedQueue队列的不同与同

    LinkedBlockingQueue 的API中,从队列中获取元素,有以下几个方法:

    1、take():原文:Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

    翻译完:从队列中取出元素E,如果队列为空,则阻塞该线程直到队列不为空拿出元素E位置;

    这样可能造成的情况是:在生产者消费中模式中,如果生产者已经生产完毕了,消费中消费完毕后,队列为空,此时用take()方法会阻塞,从而导致线程无法关闭,

    表现在运行后,eclipse中的terminae一直为红色;

    2、poll():原文:Retrieves and removes the head of this queue, or returns null if this queue is empty.

    翻译为:取出并删除队列中的首元素,如果队列为空,则返回null,不进行阻塞。

    相比于take()可以根据其他条件的判断,关闭线程,不会出现上述状态。

    举个例子:生产消费中,生产者一直生产直到生产完毕后,通知消费者,我生产完了,消费者通过pool()方法一直取出元素E,直到某次,从队列取出来的=null,

    且此时收到生产者说我生产完了,那么你就可以顺利关闭消费者线程了。

    3、poll(long timeout, TimeUnit unit):Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.

    翻译为:取出后删除头元素E,如果取不到则等到timeout时间在取,还是取不到就返回null;

    比如得到10秒,timeout为10.TimeUnit.Second

    4、peek():Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

    翻译:取出第一个元素但是不删除它,没有就返回null

    ConcurrentLinkedQueue:队列中提供了上面的poll()、peek()方法,因此用ConcurrentLinkedQueue队列不会进行阻塞,

    两者都是线程安全的。

  • 相关阅读:
    6. Flask请求和响应
    5. Flask模板
    FW:Software Testing
    What is the difference between modified duration, effective duration and duration?
    How to push master to QA branch in GIT
    FTPS Firewall
    Query performance optimization of Vertica
    (Forward)5 Public Speaking Tips That'll Prepare You for Any Interview
    (转)The remote certificate is invalid according to the validation procedure
    Change
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/9802028.html
Copyright © 2011-2022 走看看