何时使用 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 对 ListenableFuture
s 的扩展)。答案是:
- 在您需要
Executor
/ ExecutorService
(例如您的界面需要它)并且不想要并发而是 运行 您的多线程代码同步时使用它
- (上面暗示)在测试中使用它以获得可预测的结果
- 当您想自己实现
newDirectExecutorService
之类的简单 ExecutorService
,但又不想重新发明轮子时(参见 its source code)
- 如果您使用
ListenableFuture##addCallback(ListenableFuture, FutureCallback)
, newDirectExecutorService
is used by default ("for use when the callback is fast and lightweight", also mentions it's "a dangerous choice in some cases" (see javadoc)).
我只是 运行 变成这样的代码:
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 anExecutor
andnewDirectExecutorService()
if you need aListeningExecutorService
. This method will be removed in August 2016.
所以问题是:什么时候需要 MoreExecutors#directExecutor
or MoreExecutors#newDirectExecutorService
(上面提到了两者之间的区别 - ListeningExecutorService
是 Guava 对 ListenableFuture
s 的扩展)。答案是:
- 在您需要
Executor
/ExecutorService
(例如您的界面需要它)并且不想要并发而是 运行 您的多线程代码同步时使用它 - (上面暗示)在测试中使用它以获得可预测的结果
- 当您想自己实现
newDirectExecutorService
之类的简单ExecutorService
,但又不想重新发明轮子时(参见 its source code) - 如果您使用
ListenableFuture##addCallback(ListenableFuture, FutureCallback)
,newDirectExecutorService
is used by default ("for use when the callback is fast and lightweight", also mentions it's "a dangerous choice in some cases" (see javadoc)).