public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
使用LinkedBlockingQueue,但ConcurrentLinkedQueue应该更有效率,这是无阻塞和无锁?
答案 0 :(得分:1)
如果您将Runnable对象提交到队列,并且没有正在运行的线程来使用这些任务,那么它们当然不会被执行。当队列变空时,池必须阻塞并等待更多任务。因此,要实现此行为,我们在与池进行交互时使用BlockingQueue。
答案 1 :(得分:1)
答案很简单:ConcurrentLinkedQueue
不是BlockingQueue
,而是LinkedBlockingQueue
。 ThreadPoolExecutor
constructors期待BlockingQueue
,以便Executors
也可以使用BlockingQueue
的其他实现创建实例,例如SynchronousQueue
或ArrayBlokingQueue
}(取决于您在Executors
中调用的工厂方法)。
因此,更一般的问题是:为什么BlockingQueue
而不是简单的Queue
。这里答案很简单:BlockingQueue
接口有更多有用的方法。例如,一个方法判断是否可以在不违反容量限制的情况下将一个元素插入到队列中(并且不抛出异常,请检查BlockingQueue.offer()
)。或者某些方法阻止队列没有元素(同样具有定时poll()
而不是定时版本take()
)。因此,如果您要检查ThreadPoolExecutor的实现,您会看到它调用Queue
接口中遗漏的这些方便的方法。