Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 實現 Runnable 接口的基礎寫法示例

編輯:Android 開發實例

本節的主題是:如何定義一個 Runnable,並讓它的 run() 方法在獨立線程上執行。執行的 Runnable 對象通常被稱為「任務」。

Thread 和 Runnable 都是最底層的類,單靠它們能做的事有限。因此 Android 提供了更強大的封装,例如 HandlerThread、AsyncTask、IntentService。而 Thread 與 Runnable 同時也是 ThreadPoolExecutor 的基礎——後者能自動管理線程與任務隊列,甚至支持多線程並行。

定義一個實現 Runnable 的類

public class PhotoDecodeRunnable implements Runnable {
    ...
    @Override
    public void run() {
        /*
         * Code you want to run on the thread goes here
         */
        ...
    }
    ...
}

實現 run() 方法

run() 方法體就是你希望異步執行的全部代碼,內容可以是任何邏輯。但有一條紅線必須記住:Runnable 不運行在 UI 線程,因此不能直接改動 UI 對象的屬性,否則會引發 CalledFromWrongThreadException。與界面通訊的正確姿勢,是把結果交給運行在 UI 線程的 Handler 處理。

此外,在 run() 方法開頭最好主動降低線程優先級:

android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

THREAD_PRIORITY_BACKGROUND 低於默認值,這樣系統會把資源優先分配給 UI 線程,避免後台任務拖慢界面響應。

同時,建議用 Thread.currentThread() 把線程對象的引用保存下來,後續需要中斷任務時會用到。

class PhotoDecodeRunnable implements Runnable {
...
    /*
     * Defines the code to run for this task.
     */
    @Override
    public void run() {
        // Moves the current Thread into the background
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
        ...
        /*
         * Stores the current Thread in the PhotoTask instance,
         * so that the instance
         * can interrupt the Thread.
         */
        mPhotoTask.setImageDecodeThread(Thread.currentThread());
        ...
    }
...
}

把「降低優先級」與「保存線程引用」這兩件事做進 run() 的開頭,幾乎可以作為後續所有異步任務的標準起手式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved