Android thread and thread pool ----- AsyncTask (1) android development art and exploration, asynctask Thread Pool

Source: Internet
Author: User

Android thread and thread pool ----- AsyncTask (1) android development art and exploration, asynctask Thread Pool

Threads are an important concept in android. In terms of usage, threads are divided into the main thread and sub-thread, the main thread is responsible for page-related, and the sub-thread is responsible for time-consuming operations.

In android, besides the Thread itself, there is also AsyncTask IntentService HandlerThread.

AsyncTask
    public abstract class AsyncTask<Params, Progress, Result>  

1 Params parameter type
2. Progress type
3. Data Type returned by Result

You can use Void instead of parameters that are not required.

It provides four core methods:
// Called before an asynchronous task is executed. It is generally used to execute some preparation operations @ Override protected void onPreExecute () {super. onPreExecute ();} // call in the thread pool to execute an asynchronous task @ Override protected String doInBackground (String... params) {return null;} // After the asynchronous task is executed, @ Override protected void onPostExecute (String result) {super. onPostExecute (result);} // the execution in the main thread. The execution progress of the background task changes. Call @ Override protected void onProgressUpdate (Void... values) {super. onProgressUpdate (values );}

Note: 1 AsyncTask class must load 2 AsyncTask objects in the main thread must be created in the main thread 3 execute must be called in the UI thread 4 AsyncTask objects can only be executed once, that is, the execute method is called only once.
Working principle:
Public final AsyncTask <Params, Progress, Result> execute (Params... params) {return executeOnExecutor (Executor, params);} The execute method calls the executeOnExecutor method. Take a look at the executeOnExecutor method: public final AsyncTask <Params, Progress, Result> executeOnExecutor (Executor exec, params... params) {if (mStatus! = Status. PENDING) {switch (mStatus) {case RUNNING: throw new IllegalStateException ("Cannot execute task:" + "the task is already running. "); case FINISHED: throw new IllegalStateException (" Cannot execute task: "+" the task has already been executed "+" (a task can be executed only once) ") ;}} mStatus = Status. RUNNING; onPreExecute (); mWorker. mParams = params; exec.exe cute (mFuture); return this ;}

It can be seen that a thread pool is encapsulated, and then I find it.

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;      public static final Executor SERIAL_EXECUTOR = new SerialExecutor();            private static class SerialExecutor implements Executor {              final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();              Runnable mActive;                    public synchronized void execute(final Runnable r) {                  mTasks.offer(new Runnable() {                      public void run() {                          try {                              r.run();                          } finally {                              scheduleNext();                          }                      }                  });                  if (mActive == null) {                      scheduleNext();                  }              }  

From SerialExecutor, we can see that AsyncTask is a process of queuing.

The system first encapsulates the AsyncTask parameter Params as the FutureTask object, and then submits the FutureTask to the execute Process of the SerialExecutor,
The execute method hand over the FutureTask to the mTasks task queue. If there is no AsyncTask task, the SerialExecutor will scheduleNext () to execute the next task. After a task is executed, SerialExecutor executes other tasks. We can see that AsyncTask is serialized.


The AsyncTask constructor has the following code:

    mWorker = new WorkerRunnable<Params, Result>() {                  public Result call() throws Exception {                      mTaskInvoked.set(true);                            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);                      //noinspection unchecked                      return postResult(doInBackground(mParams));                  }              };  

Let's look at the run method of FutureTask:

Derived to my code snippet public void run () {if (state! = NEW |! UNSAFE. compareAndSwapObject (this, runnerOffset, null, Thread. currentThread () return; try {Callable <V> c = callable; if (c! = Null & state = NEW) {V result; boolean ran; try {result = c. call (); ran = true;} catch (Throwable ex) {result = null; ran = false; setException (ex) ;}if (ran) set (result );}} finally {// runner must be non-null until state is settled to // prevent concurrent callto run () runner = null; // state must be re-read after nulling runner to prevent // leaked interrupts int s = state; if (s> = INTERRUPTING) handlePossibleCancellationInterrupt (s );}}

It is found that the run method of FutureTask executes the call of mWorker, so the call will also be executed in the thread pool.


In mWorker's call, mTaskInvoked. set (true); indicates that the current task has been called and the doInBackground method of AsyncTask is executed.
The returned value is passed to the postResult method;

    private Result postResult(Result result) {            @SuppressWarnings("unchecked")            Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,                    new AsyncTaskResult<Result>(this, result));            message.sendToTarget();            return result;        }  

It can be seen that postResult sends a MESSAGE_POST_RESULT message through a Handler

    private static Handler getHandler() {              synchronized (AsyncTask.class) {                  if (sHandler == null) {                      sHandler = new InternalHandler();                  }                  return sHandler;              }          }                      private static class InternalHandler extends Handler {              public InternalHandler() {                  super(Looper.getMainLooper());              }                    @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})              @Override              public void handleMessage(Message msg) {                  AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;                  switch (msg.what) {                      case MESSAGE_POST_RESULT:                          // There is only one result                          result.mTask.finish(result.mData[0]);                          break;                      case MESSAGE_POST_PROGRESS:                          result.mTask.onProgressUpdate(result.mData);                          break;                  }              }          }  

After the Handler receives the MESSAGE_POST_RESULT message, it will call the finish method.

    private void finish(Result result) {              if (isCancelled()) {                  onCancelled(result);              } else {                  onPostExecute(result);              }              mStatus = Status.FINISHED;          }  

If the execution is canceled, the onCancelled method is called. Otherwise, the onPostExecute method is called.

 

Related Article

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.