Java中Thread与Runnable的区别,为什么使用Handler

本篇是我学习Java的多线程编程的备忘录,仅是我自己学习多线程时的一些片面理解,希望多多少少能帮助到观看本文的朋友,下面进入正题。

Thread是类 & Runnable是接口

  • Runnable接口仅有一个run()抽象方法。
@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();
}
  • Thread类继承并实现了Runnable接口的run()方法。
public class Thread implements Runnable {
   //仅摘取部分代码
    /* What will be run. */
    private Runnable target;

    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }
    private void init(ThreadGroup g, Runnable target, String name, long stackSize) {
         //仅摘取部分代码,其他省略
        this.target = target;
        //仅摘取部分代码,其他省略
    }
    @Override //重写Runnable接口的run()抽象方法
    public void run() {
        if (target != null) {
            target.run();
        }
    }
}

Thread类是一个线程类,它所继承的Runnable接口run()方法,就是这个线程类要完成的具体工作,使用Thread类实例不可以直接调用run ()方法完成工作,因为那样run()方法还是在main线程中完成,并没有开启子线程,要使run()方法工作在多线程下,必须使用Thread类start()方法来启动,start()会自动分配子线程并自动执行run()方法。

注意:⚠️只要是通过Thread类的start()执行,就代表Thread类实例的run()方法会在子线程中执行。有些时候多个子线程异步执行会明显提升效率,但是有时子线程执行同时需要刷新UI,那么就必须再回到main线程去刷新UI,我们要怎样在子线程中使用main线程呢?

我不告诉你

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容