何时使用 Guava sameThreadExecutor

When to use Guava sameThreadExecutor

我只是 运行 变成这样的代码:

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 {
        //
      }
    }
  });
}

这和下面的代码片段有什么区别吗?如果我理解正确的话,sameThreadExecutor使用调用submit()的同一个线程,也就是说这10个"jobs"都是在主线程上一个一个运行

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

谢谢!

首先,MoreExecutors#sameThreadExecutor 已弃用:

Deprecated. Use directExecutor() if you only require an Executor and newDirectExecutorService() if you need a ListeningExecutorService. This method will be removed in August 2016.

所以问题是:什么时候需要 MoreExecutors#directExecutor or MoreExecutors#newDirectExecutorService(上面提到了两者之间的区别 - ListeningExecutorService 是 Guava 对 ListenableFutures 的扩展)。答案是: