《Java源码分析》:Future、RunnableFuture、FutureTask

《Java源码分析》:线程池 Future、RunnableFuture、FutureTask

在使用ThreadPoolExecutor使用submit提交任务后然后交给线程池中的线程去执行,是吧

在ThreadPoolExecutor(其实是在AbstractExecutorService中)有如下几个submit方法,

    public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }
    public <T> Future<T> submit(Runnable task, T result) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }
    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }

submit然后调用executor方法,executor方法的内部实现在上篇博文已经分析过了哈。

这篇博文并不是想探讨submit方法,而是想讨论下submit的返回值Future对象.

在submit方法中我们看见,有一行这样的代码

RunnableFuture<T> ftask = newTaskFor(task);

这行代码的功能为:对我们的task进行了类型的转化,task类型是Runnable/Callable.转化成为了一个RunnableFuture对象.

根据task类型由于有两种Runnable/Callable,分别有两种不同的重载方法newTaskFor.如下:

    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);
    }

从newTaskFor函数中可以看到,就是直接调用了FutureTask的有参构造函数.

FutureTask是继承了RunnableFuture类来实现的.如下:

public class FutureTask<V> implements RunnableFuture<V> 

下面来看下RunnableFuture类的内容,如下:

    /*
     作为 Runnable 的 Future。成功执行 run 方法可以完成 Future 并允许访问其结果。 

     */
    public interface RunnableFuture<V> extends Runnable, Future<V> {
   
        /**
         * Sets this Future to the result of its computation
         * unless it has been cancelled.
         */
        void run();
    }

RunnableFuture接口比较简单,继承了Runnable、Future接口。并只有一个run方法

回到上面的所谈论的newTaskFor函数,如下:

    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new FutureTask<T>(runnable, value);
    }
    protecte
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值