Multi-Threading of Android Development series

Source: Internet
Author: User

Today in this blog, I just want to talk about the development of the program to avoid a problem-multi-threaded views and thinking.

In fact, when it comes to multithreading this name believes that as long as the contact software industry people have been familiar with, but if asked what is the multi-threaded? Why do we need multi-threading? What side effects will be caused by multithreading? In fact, these should be worthy of our deep thinking about some of the problems, because in the multi-threaded environment, often happen some unexpected things. Let's take a look at the Android platform to see exactly how multithreading should be? In fact, in Android, the system has provided us with a number of packaged multi-threaded API, such as Runable interface, asynctask background tasks.

Let's take a look at a piece of code, which is a more general way to create and open a thread.

public class Testthread extends Thread {    @Override public    void Run () {        //do your something    }}

The above method just defines a thread, and then we should call the following method to operate it.

private void Runmythread () {     new Testthread (). Start ();

In this case, we are equivalent to having a thread open. So as long as the thread is not manually interrupted, the thread will keep running while the app is in the running state. So at this point, if we have any more time-consuming operations, we can put them in the Run method. Let's take a look at the source code inside the thread, and see why the thread calls the Start method to run, why each thread is opened and then loop through the inside of the Run method? Is there a way to break a thread?

First, let's look at the class definition of thread, as follows:

public class Thread implements runnable{}

You can see that thread is actually inherited from runable, so what is runable? Let's talk about it later. into the thread class definition inside, give us the most intuitive feeling is "volatile", "ThreadLocal", there are all kinds of thread construction method. We can see in each thread construction method calls the Create method, I believe see this name everyone should be able to know what it is for, let us cut out create source to see:

private void Create (Threadgroup group, Runnable Runnable, String threadname, long stackSize) {Thread CurrentThread        = Thread.CurrentThread ();        if (group = = null) {group = Currentthread.getthreadgroup ();        } if (Group.isdestroyed ()) {throw new Illegalthreadstateexception ("group already destroyed");        } this.group = group;        Synchronized (thread.class) {id = ++thread.count;        } if (threadname = = null) {this.name = "thread-" + ID;        } else {this.name = ThreadName;        } this.target = runnable;        This.stacksize = stackSize;        This.priority = Currentthread.getpriority ();        This.contextclassloader = Currentthread.contextclassloader;        Transfer over Inheritablethreadlocals. if (currentthread.inheritablevalues! = null) {inheritablevalues = new Threadlocal.values (currentthread.inherit        Ablevalues); }//Add OurselvEs to our Threadgroup of choice this.group.addThread (this); }

From the above source code we can see very clearly that the Create method is to set the thread belongs to the threadgroup,threadname,stacksize, but there is a point needing special attention is runable object, what is it used for? We look through the code and find that it is mostly used in the Run method, with the following code:

public void Run () {        if (target! = null) {            target.run ();        }    }

We can see the thread inside the Run method, actually called the runable inside the method. This means that you can pass in a Runable object when the thread is instantiated, and then you can execute the Run method inside. But don't worry, if you think you can really create a thread, then it's wrong. We can look at the start method again, maybe you can understand.

Public synchronized void Start () {        checknotstarted ();        Hasbeenstarted = true;        Nativecreate (this, stackSize, daemon);    } Private native static void Nativecreate (Thread t, long stackSize, Boolean daemon);

Did you see it? In fact, in the Nativecreate method will use the Create method inside the parameters set to do a real creation process. Now let's go back to the original question, why did the Run method be executed after the thread was created? Specifically how to loop call, I did not find in the source code, perhaps in the C-level tune it. Then we can also see the usual sleep method, the source code is as follows:

public static void sleep (long millis, int nanos) throws Interruptedexception {if (Millis < 0) {thro        W New IllegalArgumentException ("Millis < 0:" + millis);        } if (Nanos < 0) {throw new IllegalArgumentException ("Nanos < 0:" + nanos);        } if (Nanos > 999999) {throw new IllegalArgumentException ("Nanos > 999999:" + Nanos);         }//The JLS 3rd edition, section 17.9 says: "... sleep for Zero//time...need does have observable effects."            if (Millis = = 0 && Nanos = = 0) {//... but we still has to handle being interrupted.            if (thread.interrupted ()) {throw new interruptedexception ();        } return;        } Long start = System.nanotime ();        Long Duration = (Millis * nanos_per_milli) + NANOS;        Object lock = CurrentThread (). Lock;        Wait for return early, so loop until sleep duration passes. SynChronized (Lock) {while (true) {sleep (lock, Millis, Nanos);                Long now = System.nanotime ();                long elapsed = Now-start;                if (elapsed >= duration) {break;                } Duration-= elapsed;                start = now;                Millis = Duration/nanos_per_milli;            Nanos = (int) (duration% Nanos_per_milli); }        }    }

We can see that in Java this layer just does some time above the preset judgment, the real sleep implementation is called the C-layer code:

private static native void sleep (Object lock, long millis, int nanos);

Finally, let's look at the thread break method:

public void Interrupt () {        //interrupt this thread before running the actions so, other        //threads that observe th e interrupt as a result of an action//would see that this thread was in the        interrupted state.        Nativeinterrupt ();        Synchronized (interruptactions) {for            (int i = Interruptactions.size ()-1; I >= 0; i--) {                interruptactions.get (i). run ();}}    } Private native void Nativeinterrupt ();

See the above code is actually a little puzzled is that it means that I interrupt the current thread, the system will be started by default after a thread?

Well, next we can look at runable, actually can find it is an interface, which provides a run method, the code is as follows:

Public interface Runnable {    /**     * Starts executing the active part of the class ' Code. This method was     * Called when a thread was started that had been created with a class which     * Implements {@code Runn Able}.     *    /public void run ();

Finally, let's look at the Asynctask method, what is its characteristic? How should we use it? First, let's look at the usual ways to use Android code:

public class Testasynctask extends asynctask<string,object,string> {    @Override    protected String Doinbackground (String ... params) {        return null;    }    @Override    protected void OnPostExecute (String s) {        super.onpostexecute (s);    }    @Override    protected void onprogressupdate (Object ... values) {        super.onprogressupdate (values);}    }

Define a class, and then inherit the three methods within the Asynctask replication. Let's take a look at the class definition of Asynctask:

Public abstract class Asynctask<params, Progress, result> {}

We can see that Asynctask is an abstract class that uses generics to define three parameters, representing the parameters passed in, the progress of the execution process, and the results after execution. So how do you call the Doinbackground method in Asynctask? It's time to think about how it works when we define good one asynctask. The code is as follows:

private void Testmyasynctask () {        new Testasynctask (). Execute (URL);}

So we just have to see if there is a call in the Execute method to know.

@MainThread public    Final Asynctask<params, Progress, result> executeonexecutor (Executor exec,            Params ... params) {        if (mstatus! = status.pending) {            switch (mstatus) {case                RUNNING:                    throw new Illegalstateexc Eption ("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.execute (mfuture);        return this;    }

Eventually it will call to the above method to implement our three method of replication.

Well, this blog is here. Understanding not deep enough, not to the place, welcome to shoot Bricks!

Multi-Threading of the Android Development series

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.