android-Multithreading Asynctask

Source: Internet
Author: User

Http://www.cnblogs.com/plokmju/p/android_AsyncTask.html

Asynctask, an asynchronous task, can simply perform asynchronous operations and publish execution results to the UI main thread. Asynctask is an abstract class, and its interior is actually a combination of thread and handler to implement asynchronous threading, but it forms a generic threading framework that is clearer and simpler. Asynctask should be used for relatively short operations (up to a few seconds). If you need to keep a long-running thread, you can use Threadpooexecutor or futuretask

First look at the basic usage of asynctask, because Asynctask is an abstract class, so if we want to use it, we have to create a subclass to inherit it. At the time of inheritance we can specify three generic parameters for the Asynctask class, and these three parameters are used as follows:

1. Params

Parameters that need to be passed in when executing asynctask can be used in a background task.

2. Progress

When a background task executes, the generic type specified here is used as the progress unit if you need to display the current progress on the interface.

3. Result

When the task finishes executing, if the result needs to be returned, the generic type specified here is used as the return value type.

Rules for the use of Asynctask

The following rules must be followed to use Asynctask:

    • Asynctask must be declared on the UI thread.
    • Asynctask must be instantiated on the UI thread.
    • The task must be performed through the Execute () method.
    • You cannot call OnPreExecute (), OnPostExecute (Resut), Doinbackground (Params ...), Onprogressupdate (Progress ...) directly. Method.
    • You can set the task to execute only once, if an attempt to execute again will cause an error.

The first one is because the Asynctask has built-in handler, so it works best on the main thread. However, it appears that you can also run on a child thread after calling Looper.prepare

The use of the method in the first link is very clear, the following look at the source code:

http://blog.csdn.net/guolin_blog/article/details/11711405

    • You can see that the Executeonexecutor () method was called when the source code was executed, where OnPreExecute () was called, guaranteeing his first execution of the
    • The Execute () method of the executor is then called, and the Mfuture object that was previously initialized is passed in.
    • Then came the run () method of the Futuretask class, where a child thread was opened, the call method was called, and the call method called the Doinbackground () method, which ensured that the method was executed in the child thread
    • Postresult () method, the source code is as follows:
Private result Postresult (result result) {      = shandler.obtainmessage (message_post_result,              New asynctaskresult<result> (this, Result));      Message.sendtotarget ();       return result;  }  

  As you can see, the result is actually handled with handler, returning to the main thread

Private Static classInternalhandler extends Handler {@SuppressWarnings ({"unchecked","Rawuseofparameterizedtype"}) @Override Public voidhandlemessage (Message msg) {asynctaskresult result=(Asynctaskresult) msg.obj; Switch(msg.what) { CaseMessage_post_result://there is only one resultResult.mTask.finish (result.mdata[0]);  Break;  CaseMESSAGE_POST_PROGRESS:result.mTask.onProgressUpdate (Result.mdata);  Break; }      }  }  

Inernalhandler accepts two kinds of information, if this is a message_post_result message, it executes the finish () method, if this is a message_post_progress message, The Onprogressupdate () method is executed. Then the source code for the finish () method is as follows:

Private void Finish (Result result) {      if  (iscancelled ()) {          oncancelled (result);       Else {          OnPostExecute (result);      }       = status.finished;  

As you can see, if the current task is canceled, the oncancelled () method is called, and if it is not canceled, the OnPostExecute () method is called, so that the execution of the current task is all over.

As you can see from the above, you can cancel the task at any time by calling the Cancel (Boolean) method in the run, if the successful call to IsCancelled () returns True, and the OnPostExecute () method is not executed, instead of calling Oncancelled () method.

And from the source, if this task has been executed at this time call cancel will not really end the task, but continue to execute, but change is the execution of the callback method is OnPostExecute or oncancelled.

Onprogressupdate () method source code is as follows:

protected void publishprogress (Progress ... values) {      if (!  IsCancelled ()) {          shandler.obtainmessage (message_post_progress,                  new asynctaskresult< Progress> (this, values)). Sendtotarget ();      }  }  

is also sent to handler processing, so it is run in the main thread

Serialexecutor Details:

In fact, Serialexecutor is also the place where Asynctask has made the most significant changes since the 3.0 release, which is used in the form of constants in Asynctask, so all Asynctask instances throughout the application will share the same serialexecutor

Private Static classSerialexecutor implements Executor {final Arraydeque<Runnable> Mtasks =NewArraydeque<runnable>();        Runnable mactive;  PublicSynchronizedvoidExecute (Final Runnable R) {Mtasks.offer (NewRunnable () { Public voidrun () {Try{r.run (); } finally{schedulenext ();          }              }          }); if(Mactive = =NULL) {schedulenext (); }      }        protectedSynchronizedvoidSchedulenext () {if((mactive = Mtasks.poll ())! =NULL) {Thread_pool_executor.execute (mactive); }      }  }  

As you can see, Serialexecutor is using the Arraydeque queue to manage runnable objects, and if we start a lot of tasks at once, the first time we run the Execute () method, we call Arraydeque's offer ( ) method adds the incoming Runnable object to the end of the queue, and then determines that the Mactive object is not equal to NULL, and the first run is, of course, equal to NULL, and the Schedulenext () method is called. In this method, a value is taken from the head of the queue, assigned to the Mactive object, and then called Thread_pool_executor to execute the extracted runnable object. Then there are new tasks to be executed, and also call the offer () method to add the incoming runnable to the end of the queue, but then go to the Mactive object to do a non-empty check when you will find that the Mactive object is no longer null, The Schedulenext () method is no longer called.

So will the tasks you add later never get processed? Of course not, take a look at the incoming Runnable anonymous class in the Offer () method, where a try finally block is used, and the Schedulenext () method is called in finally, guaranteeing that the method will be invoked no matter what happens. That is, every time a task executes, the next task is executed, serialexecutor mimics the effect of a single thread pool, and if we start a lot of tasks quickly, only one thread is executing at the same time, and the rest is waiting. Android Photo Wall application implementation, no more pictures are not afraid to crash the running results of the examples in this article also confirm this conclusion.

Before Android 3.0, there was no serialexecutor this class, which was built directly in Asynctask a Sexecutor constant, and the total size of the thread pool, the number of threads that can run at the same time, the code is as follows:

Private StaticFinalintCore_pool_size =5; Private StaticFinalintMaximum_pool_size = -; Private StaticFinalintKeep_alive =Ten; ...Private StaticFinal Threadpoolexecutor Sexecutor =NewThreadpoolexecutor (core_pool_size, Maximum_pool_size, Keep_alive, Timeunit.seconds, SWorkQueue, SThreadFacto  RY); 

As you can see, there are 5 threads that are allowed to run at the same time, with a total thread pool size of 128. That is, when we start 10 tasks, only 5 tasks can be executed immediately, while the other 5 tasks need to wait, when a task is completed, the 6th task will start, and so on. The maximum number of threads in a thread pool is 128, and when we try to add a 129th task, the program crashes.

So in the 3.0 version of the Asynctask change is quite large, before 3.0 Asynctask can have 5 tasks at the same time, and 3.0 after the Asynctask at the same time only one task is executed. Why are there fewer tasks that can be executed at the same time after the upgrade? This is because the updated asynctask has become more flexible and is free to configure if you do not want to use the default thread pool. For example, use the following code to start a task:

New Threadpoolexecutor ( new          linkedblockingqueue< Runnable>());   New Downloadtask (). Executeonexecutor (exec);  

This allows you to use one of our custom executor to perform tasks instead of using Serialexecutor. The effect of the above code allows 15 tasks to be executed at the same time and can store up to 200 tasks.

Places to be aware of:

Http://www.open-open.com/lib/view/open1434802647364.html

There are so many points of attention mentioned above, do you have anything else to pay attention to? Of course! When we use Asynctask to request network data in the process of developing the app, it is customary to show the progress bar in OnPreExecute, OnPostExecute close the progress bar after the data request is completed. This may seem perfect, but if your app does not explicitly specify screen orientation and configchanges, the activity restarts when the user rotates the screen, and this time your asynchronous load data thread might be requesting the network. When a new activity is re-created, a new task may be restarted to request the network, so that a previous asynchronous task inadvertently leaked, assuming you still write some other logic in OnPostExecute, this time there will be unexpected exceptions.

Generally simple data types, dealing with configchanges we are good at handling, we can directly through Onsaveinstancestate () and Onrestoreinstancestate () to save and restore. Android will call the Onsaveinstancestate () method before destroying your activity, so you can store data about the state of the app in this method. You can then recover from the OnCreate () or Onrestoreinstancestate () method.

But what about the asynctask? The problem stems from the fact that the activity was destroyed during the re-creation process and the Asynctask and previous activity was lost, resulting in some problems. Then the idea of solving the problem can also be developed in this direction. The official Android documentation also has some clues to solve the problem.

Here is another solution that uses event bus, written by an android from abroad. In the middle of the square open source Eventbus class library http://square.github.io/otto/. First, customize a subclass of Asynctask, and in the OnPostExecute method, throw the return result to the event bus, the code is as follows:

@OverrideprotectedString Doinbackground (Void ...params) {Random random=NewRandom (); FinalLongSleep = Random.nextint (Ten); Try{Thread.Sleep (Ten*6000); } Catch(interruptedexception e) {e.printstacktrace (); }        return "slept for"+ Sleep +"seconds"; } @Overrideprotected voidOnPostExecute (String result) {mybus.getinstance (). Post (Newasynctaskresultevent (result)); }

The event bus is registered in the activity's oncreate so that the message of the asynchronous thread is Otta distributed to the currently registered activity, and this time the return result is in the current activity's Onasynctaskresult, the code is as follows:

@Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.otto_layout); Findviewbyid (R.id.button). Setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Newmyasynctask (). Execute ();        }        }); Mybus.getinstance (). Register ( This); } @Overrideprotected voidOnDestroy () {mybus.getinstance (). Unregister ( This);    Super.ondestroy (); } @Subscribe Public voidOnasynctaskresult (asynctaskresulteventEvent) {Toast.maketext ( This,Event. GetResult (), Toast.length_long). Show (); }

The personal feeling of this method is quite good, of course, you can not otta this library, their own individual use of the interface callback method can also be estimated to achieve, we can try.

android-Multithreading Asynctask

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.