您的位置:首页 > 产品设计 > UI/UE

LinkedBlockingQueue 与ConcurrentLinkedQueue队列的不同与同

2016-06-20 10:25 447 查看
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队列不会进行阻塞,

这就是为什么ConcurrentLinkedQueue队列是阻塞队列而LinkedBlockingQueue
不是,当然两者都是线程安全的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  队列 java 区别