Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Thread 與 Runnable 到底差在哪?從原始碼看清真相

編輯:Android 程式設計入門

我曾經對 Thread 和 Runnable 有個錯誤理解:以為用了 Runnable 就開了新執行緒。翻過原始碼之後才搞清楚,這裡記錄下來。

其一:Runnable 只是一個介面,不會開啟執行緒

public interface Runnable {
    /**
     * Starts executing the active part of the class' code. This method is
     * called when a thread is started that has been created with a class which
     * implements {@code Runnable}.
     */
    public void run();
}

原始碼裡只有一個 run() 方法。如果你直接呼叫 runnable.run(),那段程式碼仍然跑在主執行緒(UI 執行緒)上。

實測驗證:

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            textView.setText("runable");   // 直接改 UI,居然沒報錯?
            Log.d("hello", "runable");
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    runnable.run();
    Log.d("hello", "OK");
}

結果:「runable」一定完整輸出十次之後,才轮到「OK」。這證明 run() 就是一次普通的同步方法呼叫,沒有任何並行發生。

其二:Thread 怎麼開啟執行緒?和 Runnable 什麼關係?

看類別宣告:

public class Thread implements Runnable {

最直接的一行:Thread 實作了 Runnable 介面。接著看建構子:

public Thread() {
    create(null, null, null, 0);
}

其他建構子最終也都呼叫 create():

private void create(ThreadGroup group, Runnable runnable, String threadName, long stackSize) {
    Thread currentThread = Thread.currentThread();
    if (group == null) {
        group = currentThread.getThreadGroup();
    }
    if (group.isDestroyed()) {
        throw new IllegalThreadStateException("Group already destroyed");
    }
    this.group = group;
    synchronized (Thread.class) {
        id = ++Thread.count;
    }
    if (threadName == null) {
        this.name = "Thread-" + id;
    } else {
        this.name = threadName;
    }
    this.target = runnable;      // ★ 關鍵就是這一行
    this.stackSize = stackSize;
    this.priority = currentThread.getPriority();
    this.contextClassLoader = currentThread.contextClassLoader;

    if (currentThread.inheritableValues != null) {
        inheritableValues = new ThreadLocal.Values(currentThread.inheritableValues);
    }
    this.group.addThread(this);
}

原始碼很長,但只需要看 this.target = runnable; 這一行——Thread 把你傳進來的 Runnable 存成成員變數 target。

再看 Thread 自己的 run():

public void run() {
    if (target != null) {
        target.run();      // ★ 由 Thread 幫你呼叫 Runnable 的 run
    }
}

以及 start():

/**
 * Starts the new Thread of execution. The run() method of the receiver
 * will be called by the receiver Thread itself (and not the Thread
 * calling start()).
 *
 * @throws IllegalThreadStateException - if this thread has already started.
 */
public synchronized void start() {
    checkNotStarted();
    hasBeenStarted = true;
    nativeCreate(this, stackSize, daemon);   // ★ 這裡才是真的向系統要求一條新執行緒
}

至此,兩個方法的差別就清楚了。

start() 與 run() 的差別

  • start():真正向作業系統請求一條新執行緒。呼叫後該執行緒進入就緒狀態,取得 CPU 時間片後才會執行 run(),而呼叫 start() 的地方不必等它跑完就能繼續往下走。這才是多執行緒。
  • run():只是類別上一個普通方法。直接呼叫它,程式裡仍然只有一條執行緒,執行路徑還是順序的,还得等 run() 跑完才會繼續。達不到寫執行緒的目的。

結論:只有 start() 會啟動執行緒;run() 只是一次普通的方法呼叫。 把需要並行處理的程式碼放在 run() 裡,由 start() 觸發執行緒去呼叫它,這是 JVM 的機制使然。run() 必須是 public、回傳 void。

正確寫法

Thread t = new Thread(runnable);
t.start();
Log.d("hello", "ok");

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Log.d("hello", "runable");
        }
    }
};

執行流程:

  1. 執行 Thread 建構子,this.target = runnable;。
  2. 執行 t.start(),取得 CPU 時間片後執行 run()。
  3. run() 內部呼叫 target.run(),也就是在子執行緒中執行 Runnable 的 run()。

輸出:

06-13 19:32:26.252 21369-21369/? D/hello: ok
06-13 19:32:26.252 21369-21429/? D/hello: runable
06-13 19:32:26.252 21369-21429/? D/hello: runable
...(共十次)

注意「ok」印在 21369(主執行緒),而「runable」印在 21429(子執行緒),而且順序顛倒了——這就是真開了執行緒的證據。

那為什麼前一個例子能改 UI?

前面那個 runnable.run() 裡明明寫了 textview.setText() 卻沒報錯,看起來很矛盾。但如果在按鈕的 onClick 裡改用 t.start() 去改 UI,就會立刻爆炸:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        t.start();
    }
});

錯誤訊息:

FATAL EXCEPTION: Thread-76777
android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.

原因在於 ViewRootImpl 的建立時機:

  • 在 onCreate 執行期間,View 樹尚未完成掛載,ViewRootImpl 還沒建立完成。此時的 UI 操作不會觸發「只有建立 View 的執行緒才能修改它」這項檢查,所以僥倖沒報錯。
  • 而使用者按下按鈕時,View 樹早已建立完畢,ViewRootImpl 存在且記錄了建立它的執行緒。這時任何非該執行緒的 UI 操作都會被攔下並拋出例外。

規則本身沒有例外:只有建立該 View 的執行緒才能修改和更新它。 而 ViewRootImpl 是在 ActivityThread 的主執行緒中建立的,所以只有主執行緒能更新 UI。前面那個例子只是恰好落在檢查生效之前的空窗期,不是真的允許。

實務結論

  • 需要並行 → new Thread(runnable).start(),或直接丟進執行緒池。
  • 子執行緒要更新 UI → 用 runOnUiThread()、View.post()、Handler,或 Kotlin 的協程 withContext(Dispatchers.Main)。
  • 永遠不要為了「試試看」而直接呼叫 run() 期待並行,那只是同步呼叫。
  • 別在子執行緒摸 UI,即使某個版本沒報錯也不代表安全。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved