Android中建立多線程管理器執行個體_Android

來源:互聯網
上載者:User

如果你要反覆執行一個任務,用不同的資料集(參數不同),但一次只要一個執行(任務是單線程的),IntentService符合你的需求。當需要在資源可用時自動執行任務,或允許多任務同時執行,你需要一個線程管理器管理你的線程。ThreadPoolExecutor,會維護一個隊列,當它的線程池有空時,從隊列裡取任務,並執行。要運行任務,你要做的就是把它加到隊列裡。

線程池可以並聯運行一個任務的多個執行個體,所以你要儲存代碼安全執行緒。能被多線程訪問的變數需要同步塊.更多資訊,見Processes and Threads(http://developer.android.com/guide/components/processes-and-threads.html)

定義線程池類

在它自己類中執行個體ThreadPoolExecutor.在類裡,如下操作:

為線程池使用static變數

你可能在app裡只需要一個單例的線程池,這是為了統一控制限制CPU或網路資源。如果你有不同的Runnable類型,你可能想要每種類型都有各自的線程池,但這些都可以放到一個單一的執行個體裡。比如,你可以把它聲明成全域變數:

複製代碼 代碼如下:

public class PhotoManager {
    ...
    static  {
        ...
        // Creates a single static instance of PhotoManager
        sInstance = new PhotoManager();
    }
    ...

使用private構造方法

把構造方法聲明成private,可以確保單例,這意味著你不需要在同步代碼塊裡封裝類訪問。

複製代碼 代碼如下:

 public class PhotoManager {
        ...
        /**
         * 構建用來下載和decode圖片的工作隊列和線程池,因為構造方法標記為private,
         * 對其他類不可訪問(甚至同包下的類)
         */
        private PhotoManager() {
            ...
        }

調用線程池類裡的方法來開始任務

線程池類裡定義一個方法,用來新增工作到線程池隊列,如:

複製代碼 代碼如下:

public class PhotoManager {
    ...
    // 供PhotoView調用擷取圖片
    static public PhotoTask startDownload(
        PhotoView imageView,
        boolean cacheFlag) {
        ...
        // 添加一個任務到線程池
        sInstance.
                mDownloadThreadPool.
                execute(downloadTask.getHTTPDownloadRunnable());
        ...
    }

執行個體化一個UI線程的Handler.

Handler用於與UI線程通訊,大多數UI控制項只允許在UI線程修改。

複製代碼 代碼如下:

private PhotoManager() {
    ...
        // Defines a Handler object that's attached to the UI thread
        mHandler = new Handler(Looper.getMainLooper()) {
            /*
             * handleMessage() defines the operations to perform when
             * the Handler receives a new Message to process.
             */
            @Override
            public void handleMessage(Message inputMessage) {
                ...
            }
        ...
        }
    }

判斷線程池參數

一旦你有了全部類結構,你就可以開始定義線程池。執行個體化一個線程池對象,你需要下面的值:
初始池大小,最大池大小。
線程池的線程數量主要依賴於裝置的CPU核心數.可以從系統內容中擷取。

複製代碼 代碼如下:

public class PhotoManager {
...
    /*
     * Gets the number of available cores
     * (not always the same as the maximum number of cores)
     */
    private static int NUMBER_OF_CORES =
            Runtime.getRuntime().availableProcessors();
}

這個數字可能不能反映出裝置的物理cpu核心數量;某些裝置CPU會根據系統負載自動禁用部分核心,對於這些裝置,availableProcessors()返回的是當前活躍的核心數量。

保持活躍時間和時間單位

一個進程在關閉前,保持空閑狀態的時間(可以複用進程)。時間單位在TimeUnit裡

任務隊列

ThreadPoolExecutor的列隊儲存Runnable對象。線上程中執行代碼,線程池管理器會從一個FIFO隊列裡取出一個Runnable對象,附加到線程裡。隊列實現BlockingQueue介面,在建立線程池時提供。你可以從現有實現中選一個,適應你的需求,參見ThreadPoolExecutor。下面是使用LinkedBlockingQueue的例子:

複製代碼 代碼如下:

public class PhotoManager {
    ...
    private PhotoManager() {
        ...
        // A queue of Runnables
        private final BlockingQueue<Runnable> mDecodeWorkQueue;
        ...
        // Instantiates the queue of Runnables as a LinkedBlockingQueue
        mDecodeWorkQueue = new LinkedBlockingQueue<Runnable>();
        ...
    }
    ...
}

建立線程池

調用ThreadPoolExecutor()方法初始化線程池。它會建立管理線程。因為線程池的初始大小和最大池大小是一樣的,ThreadPoolExecutor在初始化時就建立了所有線程對象,如:

複製代碼 代碼如下:
    private PhotoManager() {
        ...
        // Sets the amount of time an idle thread waits before terminating
        private static final int KEEP_ALIVE_TIME = 1;
        // Sets the Time Unit to seconds
        private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
        // Creates a thread pool manager
        mDecodeThreadPool = new ThreadPoolExecutor(
                NUMBER_OF_CORES,       // Initial pool size
                NUMBER_OF_CORES,       // Max pool size
                KEEP_ALIVE_TIME,
                KEEP_ALIVE_TIME_UNIT,
                mDecodeWorkQueue);
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.