何时使用Guava sameThreadExecutor

gfy*_*ytd 6 guava

我刚刚遇到这样的代码:

ExecutorService executorService = MoreExecutors.sameThreadExecutor();

for (int i = 0; i < 10; i++) {
  executorService.submit(new Callable<Void>() {
    @Override
    public Void call() throws Exception {
      try {
        Do some work here...
        return null;
      } catch (final Exception e) {
        throw e;
      } finally {
        //
      }
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

这和下面的代码片段有什么区别?如果我理解正确,sameThreadExecutor使用调用submit()的相同线程,这意味着所有这10个"作业"在主线程上逐个运行.

for (int i = 0; i < 10; i++) {
      try {
        Do some work here...
      } catch (final Exception e) {
        throw e;
      } finally {
        //
      }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Xae*_*ess 7

首先,MoreExecutors#sameThreadExecutor弃用:

已过时.使用,directExecutor()如果您只需要一个Executor,newDirectExecutorService()如果您需要ListeningExecutorService.此方法将于2016年8月删除.

所以问题是:你什么时候需要MoreExecutors#directExecutor或者MoreExecutors#newDirectExecutorService(上面提到的两者之间的差异 - ListeningExecutorService是番石榴对ListenableFutures 的延伸).答案是: