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

两者都是线程安全的。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值