使用FutureTask而不是Callable有什么好处? [英] what is the advantage of using FutureTask over Callable?

查看:202
本文介绍了使用FutureTask而不是Callable有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提交和轮询任务结果有两种方法

There are two approaches to submitting and polling task for result

FutureTask futureTask = new FutureTask<String>(callable);




  1. 使用 Callable <的组合/ code>和 Future 并在 ExecutorService 上提交。使用 future.get()检索结果。

  1. Use combination of Callable and Future and submit on ExecutorService. Retrieve result using future.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屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆