我刚刚意识到,在我的情况下,LinkedBlockingQueue是一个很好的解决方案--我有一个不时被填充的队列(但时间间隔很短)。我希望我的ExecutorService尽可能频繁地检查是否存在这个队列中的任何对象。
我不知道现在LinkedBlockingQueue的正确用法是什么。更早的时候,我的代码看起来像:
public void launch(){
ListeningExecutorService pool =
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threadNumber));
while(true){
if(!commandsQueue.isEmpty()){
final ListenableFuture<String> future = pool.submit(new CommandWorker(commandsQueue.poll()));
// [...]
}
}
}我在想一件事:
public void launch(){
ListeningExecutorService pool =
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threadNumber));
while(true){
Command newCommand = commandsQueue.take();
final ListenableFuture<String> future = pool.submit(new CommandWorker(newCommand));
// [...]
}
}其目的自然是使我的ListeningExecutorService尽可能快地拦截新对象。这是个好办法吗?
发布于 2014-02-20 19:31:08
你为什么要用队列呢?而不是“commandsQueue.put(命令)”,直接执行“pool.submit(新CommandWorker(命令))”。
https://stackoverflow.com/questions/21917461
复制相似问题