gpt4 book ai didi

guava - 何时使用 Guava SameThreadExecutor

转载 作者:行者123 更新时间:2023-12-02 17:30:22 34 4
gpt4 key购买 nike

我刚刚遇到这样的代码:

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 an Executor and newDirectExecutorService() if you need a ListeningExecutorService. This method will be removed in August 2016.

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

关于guava - 何时使用 Guava SameThreadExecutor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38344157/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com