concurrentlinkedqueue(concurrentlinkedqueue有哪些方法)

本文目录
concurrentlinkedqueue有哪些方法
它是一个基于链接节点的无界线程安全队列。该队列的元素遵循先进先出的原则。头是最先加入的,尾是最近加入的。
插入元素是追加到尾上。提取一个元素是从头提取。当多个线程共享访问一个公共 collection 时,ConcurrentLinkedQueue 是一个恰当的选择。该队列不允许null元素。
This implementation employs an efficient “wait-free“ algorithm based on one described in Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms by .
此实现采用了有效的“无等待 (wait-free)”算法,该算法基于 Maged M. Michael 和 Michael L. Scott 合著的 Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms 中描述的算法。
如何正确的使用java.util.ConcurrentLinkedQueue
如果直接使用它提供的函数,比如:queue.add(obj); 或者 queue.poll(obj);,这样我们自己不需要做任何同步。但如果是非原子操作,比如:
Java代码
if(!queue.isEmpty()) {
queue.poll(obj);
}
if(!queue.isEmpty()) {
queue.poll(obj);
}
我们很难保证,在调用了 isEmpty() 之后,poll() 之前,这个 queue 没有被其他线程修改。所以对于这种情况,我们还是需要自己同步:
Java代码
synchronized(queue) {
if(!queue.isEmpty()) {
queue.poll(obj);
}
}
concurrentlinkedqueue 空值 怎么处理
改用while (queue.size()》0)后
运行结果:
cost time 46422ms
结果居然相差那么大,看了下ConcurrentLinkedQueue的API原来.size()是要遍历一遍集合的,难怪那么慢,所以尽量要避免用size而改用isEmpty().

更多文章:
易语言网页api接口怎么调用(易语言,怎么读取网页json的api)
2026年10月11日 08:00
majority of(the majority of 和 a majority of的区别以及用法例句)
2026年10月11日 07:40
another time(another time和other time的区别)
2026年10月11日 05:00








