加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Thread类与Runnable接口

发布时间:2020-12-15 07:47:48 所属栏目:Java 来源:网络整理
导读:Runnable 先看看源码中对Runnable的声明 @FunctionalInterfacepublic interface Runnable { /** * When an object implementing interface codeRunnable/code is used * to create a thread,starting the thread causes the object's * coderun/code method

Runnable

先看看源码中对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();
}

可以看出,Runnable是一个函数式接口,并且里面只有一个抽象方法run(),所以继承Runnable接口必须自己手动实现run()方法。

Thread

先看看API中对Thread类的声明

public class Thread
extends Object
implements Runnable

可以看出,Thread类已经帮我们实现了Runnable接口,并且做了实现。这就是为什么继承Thread类不用重写run()方法的原因,因为Thread类已经帮我们对run方法做了实现,源码中的实现如下:

/**
 * If this thread was constructed using a separate
 * <code>Runnable</code> run object,then that
 * <code>Runnable</code> object's <code>run</code> method is called;
 * otherwise,this method does nothing and returns.
 * <p>
 * Subclasses of <code>Thread</code> should override this method.
 *
 * @see     #start()
 * @see     #stop()
 * @see     #Thread(ThreadGroup,Runnable,String)
 */
@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读