我刚刚遇到这样的代码:
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个“作业”都在主线程上一一运行。
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 anExecutor
andnewDirectExecutorService()
if you need aListeningExecutorService
. This method will be removed in August 2016.
所以问题是:你什么时候需要 MoreExecutors#directExecutor
或MoreExecutors#newDirectExecutorService
(上面提到了两者之间的区别 - ListeningExecutorService
是 Guava 对 ListenableFuture
的扩展)。答案是:
- 当您需要
Executor
/ExecutorService
(例如您的接口(interface)需要它)并且不希望并发而是同步运行多线程代码时使用它< - (如上所暗示)在测试中使用它以获得可预测的结果
- 当您想要自己实现简单的
ExecutorService
(如newDirectExecutorService
),但又不想重新发明轮子时(请参阅 its source code) - 如果您使用
ListenableFuture##addCallback(ListenableFuture, FutureCallback)
,默认情况下使用newDirectExecutorService
( "for use when the callback is fast and lightweight" ,还提到它“在某些情况下是一个危险的选择”(请参阅 javadoc ))。
关于guava - 何时使用 Guava SameThreadExecutor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38344157/