为什么Executors创建Executor使用LinkedBlockingQueue而不是ConcurrentLinkedQueue

时间:2015-08-28 07:48:43

标签: java concurrency locking java.util.concurrent

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

使用LinkedBlockingQueue,但ConcurrentLinkedQueue应该更有效率,这是无阻塞和无锁?

2 个答案:

答案 0 :(得分:1)

如果您将Runnable对象提交到队列,并且没有正在运行的线程来使用这些任务,那么它们当然不会被执行。当队列变空时,池必须阻塞并等待更多任务。因此,要实现此行为,我们在与池进行交互时使用BlockingQueue。

答案 1 :(得分:1)

答案很简单:ConcurrentLinkedQueue不是BlockingQueue,而是LinkedBlockingQueueThreadPoolExecutor constructors期待BlockingQueue,以便Executors也可以使用BlockingQueue的其他实现创建实例,例如SynchronousQueueArrayBlokingQueue }(取决于您在Executors中调用的工厂方法)。

因此,更一般的问题是:为什么BlockingQueue而不是简单的Queue。这里答案很简单:BlockingQueue接口有更多有用的方法。例如,一个方法判断是否可以在不违反容量限制的情况下将一个元素插入到队列中(并且不抛出异常,请检查BlockingQueue.offer())。或者某些方法阻止队列没有元素(同样具有定时poll()而不是定时版本take())。因此,如果您要检查ThreadPoolExecutor的实现,您会看到它调用Queue接口中遗漏的这些方便的方法。

相关问题