Java 多线程之 RunnableFuture<V>

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()

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值