Multi-Threading detailed _android of Android multithreaded processing

Source: Internet
Author: User
Tags stub touch

Handler.post (R) In fact, this does not start a new thread, just the execution of the runnable in the Run () method, but did not execute the start () method, so runnable walk or UI thread.

1. If, like this, you can manipulate the UI, but run or walk in the main thread, see the printed log thread name is main, description is the main thread.

That's why you can manipulate the UI directly in the Run method, because it's essentially a UI thread

Handler.post (New Runnable () {public

void run () {

log.e ("Current thread:", Thread.currrentThread.getName ());/ Here the print de result will be main

settitle ("haha");

   }

);

2. Getting to Looper via Handlerthread is a new thread, but it's not possible to manipulate the UI in the Run method here, but there's a downside, if you perform multiple post (r) methods that actually go to the handlerthread thread. If you do 5 times, n times, it's still a one-time and they're serial. If you download 5 pictures, you will see the picture is the first one, will go to the next one.

It has been proven that only handler with the main thread looper can manipulate the UI, while the main thread operation UI can manipulate the UI in the handler Handlermessage () method, or the UI in the handler post (R) Run method.

Handlerthread ht = new Handlerthread ("Handler thread");

Ht.start ();

Handler = new Handler (Ht.getlooper ());

Handler.post (New Runnable () {//The run () method is actually still waiting for Ht.start () to invoke public

void run () {

log.e ("Current thread:"). Thread.currrentThread.getName ());//This will be the handler thread

settitle ("haha");//This must be an error

//  Android.view.viewroot$calledfromwrongthreadexception:only the original thread that created a view hierarchy can touch its Views.

   }

});

So what to do, oh, can not participate in the construction of a handler. Use this handler to send messages and process messages, using the handler above to open a new thread.

MainHandler = new Handler () {

protecket void handlermessage (Message msg) {

settitle ("haha");//So there won't be an error.

}
   }

Handler.post (new Runnable () {//The run () method is actually waiting for Ht.start () to call public

void Run () {

log.e ("Current thread:"). Thread.currrentThread.getName ())///This will be the handler thread

mainhandler.sendempetmessage ();//Send a message with MainHandler

//settitle ("haha");//This must be an error

//android.view.viewroot$calledfromwrongthreadexception:only the original Thread that created a view hierarchy can touch its views.

   }

);

Print log:

3. In fact, the 2nd method appears to be troublesome and inefficient, using 2 handler, one to initiate the thread, and one to process the message. The handler of the originating thread must have a looper, so you also instantiate a handerthread, and the handler that processes the message does not need looper because it has the main thread's looper by default, so you can process the UI in this handler.

You can actually just instantiate a handler, build an handler in the main thread, and then send and process the message. The task of creating a thread is not handler, directly using the new thread (r), and then processing the logical transaction in the R's Run () method.

Download 5 pictures In this mode, you may not see a picture next to a show, may be the 2nd one out first, may also come out 3, 5 threads very random.

private void Loadimagesbythread (final String url,final int id) {//Create multiple threads new Thread (new 
     
    Runnable () { 
 
      @Override public 
      Void Run () { 
        //TODO auto-generated the method stub 
        log.e ("Current thread:", "" +thread.currentthread (). GetName ()); 
        Drawable drawable = null; 
        try { 
          drawable = drawable.createfromstream (new URL (URL). OpenStream (), "image.gif"); 
        Malformedurlexception e) { 
          //TODO auto-generated catch block 
          e.printstacktrace (); 
        } catch (IOException e) { 
          //TODO auto-generated catch block 
          e.printstacktrace (); 
        } 
        Message msg = Mainhandler.obtainmessage (); 
        Msg.what =; 
        MSG.ARG1 = ID; 
        Msg.obj = drawable; 
        Msg.sendtotarget (); 
         
      } 
       
    }). Start (); 
  } 

Print log:

4.AsyncTask

Using the asynchronous task Architecture Multi-task model is not very robust, you have to create multiple asynctask instances. A asynctask only executes once, cannot repeat, the fast-food thread, run out once.

To implement the Asynctask subclass, the most important two methods, one is Doinbackground (params), and one is onpostexecute (result). Processing the time-consuming transaction in the Doinbackground () method and returning the result, the returned value will be in the OnPostExecute method as an argument, and then the result can be displayed on the UI in OnPostExecute ().

Steps:

① instantiation Asynctask:

Instantiate the Asynctask and then pass the task.exec (pamas); The argument list is dynamic, can be one, and can make multiple, variable lengths.

Asynctask<params,values,reslut>, the first parameter is passed into this method Doinbackground (params), the second parameter is the value of the data update, and the third is the result of processing the transaction return.

②onpreexecute Method:

This method has no parameters and no return value, so you can do some reminders in this method. For example, show a dialog, or play a toast tell the user to start downloading.

③doinbackground (params) method:

Entering the ASYNCTASK internal structure, the Reslut Doinbackground (params) method will be executed first, which will handle the time-consuming transaction, and the EXEC () parameter will be passed into this method to do the parameter, and the return value will be the OnPostExecute () The parameters. If you want to update your progress, you need to perform the publicprogress () method.

④onprogressupdate (values) method:

The parameter of this method must execute the Publicprogress () method in the Doinbackground () method, which will pass the parameter into the Onprogressupdate () method, and then do some UI update display in this method. For example, the value of the progress bar can be changed dynamically through this values value.

⑤onpostexecute (Result) method:

Here is the way the transaction is done, and the results of the Doinbackground method will be passed here if the method returns the data. In this method, the UI can be processed, and the processed data can be displayed on the UI. Like pictures, words, all the results you want.

private void Loadimagebyasynctask (final String url,final int id) {//Build asynchronous task so that you don't have to handler to process messages Downloadtask task = new 
    Downloadtask ();  
 
    Task.execute ("" +id,url);//asynctask not repeatable} class Downloadtask extends asynctask<string,integer,drawable>{ 
    int id; @Override protected drawable doinbackground (String ... params) {//params save URL and control ID two data//TODO auto-generated m 
      Ethod stub log.e ("Current thread:", "" +thread.currentthread (). GetName ()); 
      Drawable drawable = null; 
      This.id = Integer.parseint (Params[0]); 
      try {drawable = Drawable.createfromstream (new URL (params[1)). OpenStream (), "image.gif"); 
      catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace (); 
      catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
    return drawable; @Override protected void OnPostExecute (drawable resUlt) {//TODO auto-generated Method stub super.onpostexecute (result); 
    ((ImageView) MainActivity.this.findViewById (ID)). setimagedrawable (result); @Override protected void OnPreExecute () {//TODO auto-generated method stub super.onpreexecut 
    E (); 
      @Override protected void Onprogressupdate (Integer ... values) {//TODO auto-generated method stub 
    Super.onprogressupdate (values); 
 } 
 
     
  }

The log that is printed here

5.ExecutorServie thread Pool

Created by executors static methods, there are generally three kinds:

1. Single thread: Executors.newsinglethreadexecutor ();

2. Fixed number of threads: Executors.newfixedthreadpool ();

3. Dynamic thread: Executors.newcachedthreadpool ();

Here we use a fixed 5 thread to apply, using the method is to create the Executorservice object, and then execute submit (R) to initiate a Runnable object. The advantage of using thread pool to manage is that it can guarantee the system to run stably, apply with a lot of threads, high workload situation use, if want to show 1000 picture if create 1000 threads to load, guarantee the system will die. The thread pool can be used to avoid this problem, you can use 5 threads in turn, 5 groups, the finished thread is not directly recycled but wait for the next execution, so that the overhead of the system can be reduced a lot.

private void Loadimagesbyexecutors (final String url,final int id) {Service.submit (new Runnable () {@Ov Erride public void Run () {//TODO auto-generated the method stub log.e ("Current thread:", "" +thread.currentthr 
         
        EAD (). GetName ()); 
          try {final drawable drawable = drawable.createfromstream (new URL (URL). OpenStream (), "image.gif"); Mainhandler.post (New Runnable () {@Override public void run () {//This will run on the main thread//TOD 
            O auto-generated Method Stub ((ImageView) MainActivity.this.findViewById (ID)). setimagedrawable (drawable); 
           
        } 
          }); 
        catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace (); 
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
     
  } 
         
      } 
       
    }); 
 }

Log:

In fact, it may not be clear that the first one is not multiple threads.

1.loadImagesByHandler () The Handler.post () method is used to build two handler for communication.

2.loadImagesByThread (), this is the direct new thread () initiated by threads, processing messages in the handler of the main thread

3.loadImageByAsyncTask (), this is an asynchronous task, all implemented in its internal structure, can operate the UI inside.

4.loadImagesByExecutors () is a thread pool, so that the threads can be controlled to ensure stable operation.

In fact, the most commonly used is the latter three, the second use of flexible, simple, but not suitable for a large number of tasks; The third is generally applicable to a single task, one-time tasks, the fourth is generally used for large quantities, high-density implementation of the use of scenarios, such as bulk load pictures, bulk download files

Take a look at the picture:

Full Source:

Package com.bvin.exec; 
Import java.io.IOException; 
Import java.net.MalformedURLException; 
Import Java.net.URL; 
Import Java.util.concurrent.ExecutorService; 
 
Import java.util.concurrent.Executors; 
Import android.app.Activity; 
Import android.graphics.drawable.Drawable; 
Import Android.os.AsyncTask; 
Import Android.os.Bundle; 
Import Android.os.Handler; 
Import Android.os.HandlerThread; 
Import Android.os.Message; 
Import Android.util.Log; 
Import Android.view.View; 
Import Android.widget.Button; 
 
Import Android.widget.ImageView; The public class Mainactivity extends activity {/** called the ' when the ' is ' the ' activity ' is the ' the '. * Private created H 
  Andler; 
  Private Button BT;  Private Handler MainHandler = new Handler () {@Override public void Handlemessage (msg) {//TODO 
      auto-generated method Stub super.handlemessage (msg); if (msg.what = = 2012) {//UI can be processed as long as the main thread (ImageView) MainActivity.this.findViewById (msg.arg1)). Setimagedrawable ((drawable) msg.obj); 
   
  } 
    } 
     
     
  }; 
   
  Private Executorservice service = Executors.newfixedthreadpool (5); 
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
    Initviews (); 
    Handlerthread ht = new Handlerthread ("Down image thread"); 
    Ht.start (); Handler = new Handler (Ht.getlooper ()) {//If Looper is available then this handler cannot process UI @Override public void Handlemessage (msg) 
         
         
      {//TODO auto-generated Method Stub super.handlemessage (msg); 
     
  } 
       
    }; 
    private void Initviews () {BT = (Button) Findviewbyid (R.ID.BT); 
        Bt.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) { TODO auto-generated Method Stub loadimagesbyexecutors ("Http://news.baidu.com/z/resource/r/image/2012-11-23/23c1625aca99f02c50d8e510383a34e7.jpg ", R.ID.IV1); Loadimagesbyexecutors ("http://news.baidu.com/z/resource/r/image/2012-11-23/ 
        C4698d97ef6d10722c8e917733c7beb3.jpg ", r.id.iv2); Loadimagesbyexecutors ("http://news.baidu.com/z/resource/r/image/2012-11-23/ 
        F332ffe433be2a3112be15f78bff5a40.jpg ", r.id.iv3); Loadimagesbyexecutors ("http://news.baidu.com/z/resource/r/image/2012-11-23/ 
        6ff8a9c647a1e80bc602eeda48865d4c.jpg ", r.id.iv4); Loadimagesbyexecutors ("http://news.baidu.com/z/resource/r/image/2012-11-23/ 
      F104d069f7443dca52a878d779392874.jpg ", R.ID.IV5); 
  } 
    }); 
     
     
    private void Loadimagesbyhandler (final String url,final int id) {//new thread by owning Looper handler.post (runnable) 
        Handler.post (New Runnable () {//If handler does not have looper then it cannot build a new thread @Override public void run () { 
        TODO auto-generated Method Stub log.e ("Current thread:", "" +thread.currentthread (). GetName ()); 
        Drawable drawable = null; 
     try {     drawable = drawable.createfromstream (new URL (URL). OpenStream (), "image.gif"); 
        catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace (); 
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
        }//systemclock.sleep (2000); 
        ((ImageView) MainActivity.this.findViewById (ID)). setimagedrawable (drawable); 
        Message msg = Mainhandler.obtainmessage (); 
        Msg.what = 2012; 
        MSG.ARG1 = ID; 
        Msg.obj = drawable; 
      Msg.sendtotarget (); 
     
     
  } 
       
    }); The private void Loadimagesbythread (final String url,final int id) {//new thread to create multiple threads (new Run  Nable () {@Override public void run () {//TODO auto-generated Method Stub log.e ("Current thread:", 
        "" +thread.currentthread (). GetName ()); 
        Drawable drawable = null; try {Drawable = drawable.createfromstream (new URL (URL). OpenStream (), "image.gif"); 
        catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace (); 
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
        Message msg = Mainhandler.obtainmessage (); 
        Msg.what = 2012; 
        MSG.ARG1 = ID; 
        Msg.obj = drawable; 
         
      Msg.sendtotarget (); 
  }). Start (); } private void Loadimagebyasynctask (final String url,final int id) {//Build asynchronous task so that you don't have to handler to process messages Downloadtask Tas 
    K = new Downloadtask (); 
    Task.execute ("" +id,url);//asynctask not repeatable} private void Loadimagesbyexecutors (final String url,final int id) { Service.submit (New Runnable () {@Override public void run () {//TODO auto-generated met 
   Hod stub log.e ("Current thread:", "" +thread.currentthread (). GetName ());      
        try {final drawable drawable = drawable.createfromstream (new URL (URL). OpenStream (), "Image.gif" 
          ); Mainhandler.post (New Runnable () {@Override public void run () {//This will run on the main thread//TOD 
            O auto-generated Method Stub ((ImageView) MainActivity.this.findViewById (ID)). setimagedrawable (drawable); 
           
        } 
          }); 
        catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace (); 
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
     
  } 
         
      } 
       
    }); 
    Class Downloadtask extends asynctask<string,integer,drawable>{int id; @Override protected drawable doinbackground (String ... params) {//params save URL and control ID two data//TODO auto-generated m Ethod stub log.e ("Current thread:", "" +thread.currentthread (). GetName ()); 
      Drawable drawable = null; 
      This.id = Integer.parseint (Params[0]); 
      try {drawable = Drawable.createfromstream (new URL (params[1)). OpenStream (), "image.gif"); 
      catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace (); 
      catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
    return drawable; @Override protected void OnPostExecute (drawable result) {//TODO auto-generated method stub s 
      Uper.onpostexecute (result); 
    ((ImageView) MainActivity.this.findViewById (ID)). setimagedrawable (result); @Override protected void OnPreExecute () {//TODO auto-generated method stub super.onpreexecut 
    E (); 
      @Override protected void Onprogressupdate (Integer ... values) {//TODO auto-generated method stub 
    Super.onprogressupdate (values); 
 
     
}  } 
} 



 

Above is the Android multi-threading data collation, follow-up continue to supplement the relevant knowledge, thank you for your support to this site!

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.