天天看點

android AsyncTask 隻能線上程池裡單個運作的問題

android 的AysncTask直接調用Execute會在在一個線程池裡按調用的先後順序依次執行。

如果應用的所有網絡擷取都依賴這個來做,當有一個網絡請求柱塞,就導緻其它請求也柱塞了。

在3.0 以後引入了新的方法。可以不在一個線程池裡運作。

class TaskHelper {

    public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task) {
        execute(task, (P[]) null);
    }

    @SuppressLint("NewApi")
    public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task, P... params) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
        } else {
            task.execute(params);
        }
    }
}      

asyncTask.execute

Note: this function schedules the task on a queue for a single background thread or pool of threads depending on the platform version. When first introduced, AsyncTasks were executed serially on a single background thread. Starting with android.os.Build.VERSION_CODES.DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. After android.os.Build.VERSION_CODES.HONEYCOMB, it is planned to change this back to a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can use the executeOnExecutor version of this method with THREAD_POOL_EXECUTOR; however, see commentary there for warnings on its use. 

This method must be invoked on the UI thread.必須UI線程中調用

注意:這個函數讓任務是以單線程隊列方式或線程池隊列方式運作,依賴于平台版本而有所不同。asyncTask首次引入時,這個函數會讓任務以背景單線程串行方式執行。從android.os.Build.VERSION_CODES.DONUT(android 1.6)開始,它讓允許任務線上程池中多任務并行執行。但在 android.os.Build.VERSION_CODES.HONEYCOMB(android 3.0)之後,它又該回去了,變成了單線程執行的模式,原因是多線程并行執行容易引發問題。如果你真想并行執行任務,你可以使用另外一個版本:使用THREAD_POOL_EXECUTOR參數的executeOnExecutor方法,但要注意使用警告提示

anyncTask.executeOnExecutor

This method is typically used with THREAD_POOL_EXECUTOR to allow multiple tasks to run in parallel on a pool of threads managed by AsyncTask, however you can also use your own Executor for custom behavior. 

Warning: Allowing multiple tasks to run in parallel from a thread pool is generally not what one wants, because the order of their operation is not defined. For example, if these tasks are used to modify any state in common (such as writing a file due to a button click), there are no guarantees on the order of the modifications. Without careful work it is possible in rare cases for the newer version of the data to be over-written by an older one, leading to obscure data loss and stability issues. Such changes are best executed in serial; to guarantee such work is serialized regardless of platform version you can use this function with SERIAL_EXECUTOR. 

This method must be invoked on the UI thread.

Parameters:

exec The executor to use. THREAD_POOL_EXECUTOR is available as a convenient process-wide thread pool for tasks that are loosely coupled.

這個方法通常和THREAD_POOL_EXECUTOR一起使用,允許多個任務在由AsyncTask管理的線程池中并行執行,但是您你也可以使用自定義行為的Executor。