Android Multithreaded Learning Example detailed _android

Source: Internet
Author: User
Tags message queue prepare thread class

The example of this article is an analysis of Android multithreading. Share to everyone for your reference, specific as follows:

There is also the concept of multithreading under Android, in C + +, a child thread can be a function, generally a function with a loop to handle some data, the priority thread is only a complex operation, so it may not need a while loop, the operation is complete, the function ends, the thread is destroyed. For those threads that need to be controlled, we are generally associated with mutual exclusion locks to control the progress of the thread, which is common when we create child threads, a thread that has a message loop.

The message loop is a useful threading method that once used C to implement a message loop mechanism under Linux, to add data to a message queue, and then to wait for the message to return asynchronously. When the message queue is empty, the thread is suspended, waiting for the new message to join. This is a very common mechanism.

In Android, where threads are divided into threads with message loops and threads without message loops, threads with message loops typically have a looper, the new concept of Android. Our primary thread (UI thread) is the thread of a message loop. In response to this message cycle mechanism, we introduce a new mechanism handle, we have a message loop, we have to send the message loop to the corresponding message, custom messages will generally have their own corresponding processing, message send and purge, message processing, these are encapsulated in the handle inside, Note that handle is only for those threads that have looper, whether it is a UI thread or a child thread, as long as you have looper, I can add things to your message queue and do the appropriate processing.

But there is one more thing about UI-related things that you can't put in a child thread, because a child thread cannot manipulate the UI, only data, systems, and other non-UI operations.

So under what circumstances can our child threads be considered a thread with a looper? How do we get the looper handle of it?

Looper.mylooper (); Get the current Looper

Looper.getmainlooper () Gets the lopper of the UI thread

Let's look at the initialization function of handle, if there is no parameter, then he uses the current looper by default, if there is a looper parameter, it is the looper of the corresponding thread.

If Looper.prepare () is invoked in one thread, then the system automatically creates a message queue for the thread, then calls Looper.loop (), and then goes to the message loop, after which you can send messages, fetch messages, and process messages. This how to send messages and how to process messages can be done through handle in other threads, but only if our Hanle knows the looper of this child thread, but if you do not run Looper.mylooper () on a child thread, you generally do not get the looper of the child thread.

public void Run () {
  synchronized (mlock) {
    looper.prepare ();
    Do something
  }
  looper.loop ();
}

So a lot of people do this: I create a new handle directly in the child thread, and then send a message in the child thread, so that we lose the meaning of multithreading.

Class Mythread extends thread{
   private Ehandler mhandler;
   public void Run () {
     looper mylooper, Mainlooper;
     Mylooper = Looper.mylooper ();
    Mainlooper = Looper.getmainlooper ();
    String obj;
    if (Mylooper = = null) {
         Mhandler = new Ehandler (mainlooper);
         obj = "Current thread has no looper!";
    }
    else {
       Mhandler = new Ehandler (mylooper);
       obj = "This is from current thread.";
    }
    Mhandler. Removemessages (0);
    Message m = Mhandler. Obtainmessage (1, 1, 1, obj);
    Mhandler. SendMessage (m);
   }


Can let other threads to control our handle, can put private ehandler mhandler, so that our message and processing messages can be defined outside, so as to increase the beauty of the program code, the structure more clear.

In the case of any handle, the inside must be overloaded with a function

public void Handlemessage (msg)

This function is our message processing, how to deal with, it is entirely up to you, and then through Obtainmessage and SendMessage to generate and send messages, Removemessages (0) to clear message queues. Google is really smart, and this kind of framework makes it easier for us to write code.

Sometimes, our child threads want to change the UI, this time should not be modified in the child thread, get the looper of the UI thread, and then send the message.

Let's take a look at Gao's code:

Class Ac01 extends Activity {//... public void OnClick (View v) {switch (V.getid ()) {Case 101:
          t = new mythread ();
         T. Start ();
       break;
            Case 102:finish ();
       break; }//------------------------------------------------------class Ehandler extends Handler {public Ehandler (Loop
      Er looper) {super (Looper);
    @Override public void Handlemessage (Message msg) {TV. SetText ((String) msg. obj);  }//------------------------------------------------------class Mythread extends thread{private Ehandler Mhandler
   ;
    public void Run () {Looper mylooper, mainlooper;
    Mylooper = Looper.mylooper ();
    Mainlooper = Looper.getmainlooper ();
    String obj;
        if (Mylooper = = null) {Mhandler = new Ehandler (mainlooper);
    obj = "Current thread has no looper!";
       else {Mhandler = new Ehandler (mylooper); obj = "This is F"Rom current thread. ";
    } mhandler. removemessages (0);
    Message m = Mhandler. Obtainmessage (1, 1, 1, obj);
   Mhandler. SendMessage (m);

 }
 }
}

Completely unintelligible, a lump of dog excrement. Let's see, in the run above

Looper mylooper, Mainlooper;
Mylooper = Looper.mylooper (); Obviously this will return empty, because you have not prepare, will not return Looper.
mainlooper = Looper.getmainlooper ();

Suggest everybody in see Looper of time Don't look Gao book, feel he also not very understand, but also confuse me. Speaking so much, it is entirely his own understanding, his own understanding is very complex, the key is to complicate the simple problem, and the complex after the things are wrong. Let's look at the source code for the Goole Music app.

In Mediaplaybackactivity.java, we can take a look at the two sentences in the OnCreate:

Malbumartworker = new Worker ("album art Worker");
Malbumarthandler = new Albumarthandler (Malbumartworker.getlooper ());

Obviously these two sentences are constructed with a child thread. And this child thread is a looper thread, and it's a great idea to use the Malbumartworker.getlooper () function, because we know that we have only one way to get the looper of a child thread: it is to call in a child thread Looper.mylooper (), and this function will be called after we perpare to get the correct looper, but he used this here what East Getlooper, do not know how it is achieved?

Here is a general idea, we call the Mylooper () after the prepare of the child thread, and then save in a member variable, this getlooper return this thing, but here will encounter a very prominent problem of multithreading, synchronization. We call Malbumartworker.getlooper () in the parent thread, but want this to return the correct looper must require our child thread to run the prepare, but this thing is actually child thread run, how can we guarantee?

How do we see how Google is implemented?

 private class Worker implements Runnable {private final Object Mlock = new Object ()
    ;
    Private Looper Mlooper; /** * Creates a worker thread with the given name.
     The thread * then runs a {@link android.os.Looper}.
      * @param name A name for the new thread */Worker (String name) {Thread t = new thread (null, this, name);
      T.setpriority (thread.min_priority);
      T.start ();
          Synchronized (Mlock) {while (mlooper = = null) {try {mlock.wait (); The catch (Interruptedexception ex) {}}} is public Looper getlooper () {return mloop
    Er
        public void Run () {synchronized (Mlock) {looper.prepare ();
        Mlooper = Looper.mylooper ();
      Mlock.notifyall ();
    } looper.loop ();
    public void Quit () {mlooper.quit (); }
}

We know that the constructor of a thread class is done in the main thread, so in our worker's constructor we create a thread and then let this thread run, this thread is created to specify a runnabl, here is our worker itself, in the main thread call T.start (), after which our child threads have been created, and begin to execute the work run method. Then the following code is very artistic:

Synchronized (Mlock) {while
    (mlooper = = null) {
      try {
        mlock.wait ();
      } catch (Interruptedexception ex) { c5/>}}}


We start to wait for our child thread to assign value to Mlooper, and if we do not assign values, we continue to wait, and then our child thread after running the Run method, after assigning the mlooper, notifies the worker enough to wait in the function and then our constructor completes, so we say:

Malbumartworker = new Worker ("album art Worker");

The sentence itself is blocked, it created a child thread, opened the child thread, and wait for the child thread to the Mlooper assignment, after the assignment is completed, this function is returned, so as to ensure that the looper of our child thread is absolutely correct, the idea is very creative. worthy of reference.

For more information on Android-related content readers can view the site topics: "The Android thread and message mechanism usage Summary", "Android Development introduction and Advanced Course", "Android Debugging techniques and common problem solving method summary", " Android Multimedia How-to Summary (audio, video, audio, etc), summary of Android Basic components usage, Android View tips Summary, Android layout layout tips and a summary of Android controls usage

I hope this article will help you with your Android programming.

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.