实现BlockingQueue:SynchronousQueue和LinkedBlockingQueue之间有什么区别?
- 论坛
- 实现BlockingQueue:SynchronousQueue和LinkedBlockingQueue之间有什么区别?
11 浏览
实现BlockingQueue:SynchronousQueue和LinkedBlockingQueue之间有什么区别?
我看到了这些BlockingQueue的实现,但不明白它们之间的区别。我目前的结论是:
- 我永远不会需要SynchronousQueue
- LinkedBlockingQueue确保先进先出,BlockingQueue必须使用参数true来使其先进先出
- SynchronousQueue破坏了大多数集合方法(contains、size等)
那么我何时需要SynchronousQueue呢?这个实现的性能是否优于LinkedBlockingQueue?
为了更复杂一些...为什么Executors.newCachedThreadPool使用SynchronousQueue,而其他两个(Executors.newSingleThreadExecutor和Executors.newFixedThreadPool)使用LinkedBlockingQueue?
编辑
第一个问题已解决。但我仍然不明白为什么Executors.newCachedThreadPool使用SynchronousQueue,而其他两个(Executors.newSingleThreadExecutor和Executors.newFixedThreadPool)使用LinkedBlockingQueue?
我所理解的是,使用SynchronousQueue时,如果没有空闲线程,生产者将被阻塞。但由于线程数实际上是无限制的(如果需要会创建新线程),这种情况永远不会发生。那么为什么它要使用SynchronousQueue呢?