• 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队列不会进行阻塞,

    两者都是线程安全的。

  • 相关阅读:
    【Udacity】线性回归方程 Regression
    【Android】Warning :uninstalling will remove the application data!
    【Udacity】数据的差异性:值域、IQR、方差和标准差
    docker部署一个简单的mian.py项目文件
    ubuntu安装goland
    Go 语言变量、常量
    Go 语言数据类型
    linux 之文件重命名
    linux 下新建文件自动加锁的解决办法
    go之linux安装
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/9802028.html
Copyright © 2020-2023  润新知