Java中Thread與Runnable的區(qū)別,為什么使用Handler

本篇是我學(xué)習(xí)Java的多線程編程的備忘錄,僅是我自己學(xué)習(xí)多線程時的一些片面理解,希望多多少少能幫助到觀看本文的朋友,下面進入正題。

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類繼承并實現(xiàn)了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類實例不可以直接調(diào)用run ()方法完成工作,因為那樣run()方法還是在main線程中完成,并沒有開啟子線程,要使run()方法工作在多線程下,必須使用Thread類start()方法來啟動,start()會自動分配子線程并自動執(zhí)行run()方法。

注意:??只要是通過Thread類的start()執(zhí)行,就代表Thread類實例的run()方法會在子線程中執(zhí)行。有些時候多個子線程異步執(zhí)行會明顯提升效率,但是有時子線程執(zhí)行同時需要刷新UI,那么就必須再回到main線程去刷新UI,我們要怎樣在子線程中使用main線程呢?

我不告訴你

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容