天天看點

asyncTask 的execute和executeOnExecutor 方法

asyncTask.execute 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。

警告:因為執行操作順序并未定義,通常情況下,允許多個任務線上程池中并行執行,其結果并非是你想要的。例如:這些任務都要去修改某個狀态值(諸如點選按鈕寫檔案),因為沒有确定的修改順序,舊的修改可能會覆寫新修改的版本内容,導緻不穩定資料丢失而變成一個穩定的問題。是以這種任務最好是串行執行;確定這些任務串行執行而不依賴于平台版本的方法是,使用SERIAL_EXECUTOR

 看了這篇文章,http://blog.csdn.net/hitlion2008/article/details/7983449, 講的挺好

  更多解釋:http://blog.csdn.net/guolin_blog/article/details/11711405

   http://www.cnblogs.com/fotransit/archive/2013/04/17/3025937.html

    本文轉自 一點點征服   部落格園部落格,原文連結:http://www.cnblogs.com/ldq2016/p/6844198.html,如需轉載請自行聯系原作者

繼續閱讀