作者简介:大家好,我是码炫码哥,前中兴通讯、美团架构师,现任某互联网公司CTO,兼职码炫课堂主讲源码系列专题
代表作:《jdk源码&多线程&高并发》,《深入tomcat源码解析》,《深入netty源码解析》,《深入dubbo源码解析》,《深入springboot源码解析》,《深入spring源码解析》,《深入redis源码解析》等
联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬。码炫课堂的个人空间-码炫码哥个人主页-面试,源码等
在使用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();
}

最低0.47元/天 解锁文章
640

被折叠的 条评论
为什么被折叠?



