https://www.cnblogs.com/dolphin0520/p/3949310.html
通过源代码我们可以看到,FutureTask类是RunnableFuture的实现:public class FutureTask<V> implements RunnableFuture<V>
。所以追踪一下,我们可以看到RunnableFuture接口的定义如下:
package java.util.concurrent;
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
这里初看很奇怪,因为在Runnable方法中已经有run()方法,为什么这里还要再定义一次呢。通过查看Runnable接口源码我们发现:
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
由源码可见,run()
方法是抽象方法。根据Java的语法,接口派生的时候,需要实现抽象函数,因此 RunnableFuture 中重写的run()
方法实现上是对Runnable中的run()
方法的实现。
通过以上源码分析,我们可知 RunnableFuture 接口就是对 Runnable 和 Future 这两个接口的合并,它包括了两个接口的所有方法,所以可以用于执行两类接口的操作,即无返回值的run()
和有返回值的 get()
。