使用FutureTask而不是Callable有什么好处? [英] what is the advantage of using FutureTask over Callable?
问题描述
提交和轮询任务结果有两种方法
There are two approaches to submitting and polling task for result
FutureTask futureTask = new FutureTask<String>(callable);
-
使用
Callable <的组合/ code>和
Future
并在ExecutorService
上提交。使用future.get()
检索结果。
Use combination of
Callable
andFuture
and submit onExecutorService
. Retrieve result usingfuture.get()
.
Future future = service.submit(callable);
使用 FutureTask
。这将包装 Callable
,然后使用 FutureTask
检索结果。
Use FutureTask
. This will wrap Callable
and then retrieve result using FutureTask
.
service.execute(task);
使用<$ c的优点是什么$ c> FutureTask over Callable
+ Future combination?
What is the advantage of using FutureTask
over Callable
+ Future combination ?
推荐答案
几乎肯定都没有。快速浏览 AbstractExecutorService 的%28java.lang.Runnable%29rel =noreferrer> GrepCode 显示这些方法中的每一个都是最终包装 Callable
/ Runnable
在 Future
中为您服务。
Almost certainly none at all. A quick browse on GrepCode of the AbstractExecutorService
shows each of these methods are simply helper methods that ultimately wrap the Callable
/Runnable
in a Future
for you.
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
public Future<?> submit(Runnable task) {
// ...
RunnableFuture<Object> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
public <T> Future<T> submit(Runnable task, T result) {
// ...
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
public <T> Future<T> submit(Callable<T> task) {
// ...
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
这篇关于使用FutureTask而不是Callable有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!