Android multithreaded Research (1)--thread base and source code profiling

Source: Internet
Author: User

From today on we have a look at the multi-threaded knowledge of Android, Android easy to get started, but to complete a good product is not easy, let us start from the thread step into the android inside.

First, Thread Foundation recall

Package Com.maso.test;public class Traditionalthread {public static void main (string[] args) {/* * thread First creation method */thread THR Ead1 = new Thread () {@Overridepublic void run () {try {sleep ()} catch (Interruptedexception e) {e.printstacktrace ()} while (true) {System.out.println (Thread.CurrentThread (). GetName ());}}; Thread1.start ();/* * Another way to create a thread */thread thread2 = new Thread (new Runnable () {@Overridepublic void run () {try {Thread.sle EP (1000);} catch (Interruptedexception e) {e.printstacktrace ();} while (true) {System.out.println (Thread.CurrentThread (). GetName ());}}); Thread2.start ();/* * Thread Call Priority */new thread (new Runnable () {@Overridepublic void run () {try {thread.sleep ()} catch (in Terruptedexception e) {e.printstacktrace ();} while (true) {System.out.println ("Runnable");}}) {public void Run () {try {sleep ()}, catch (Interruptedexception e) {e.printstacktrace ();} while (true) {System.out.println ("Thread");}};}. Start ();}}
The above code is two ways to create a thread that we are all very familiar with, assuming that you are unfamiliar with the Java Thread Foundation first.


Open the source code of the thread class to see that the thread class has 8 constructors, let's first look at the source of the two constructors above.

    Public Thread () {        init (null, NULL, "thread-" + nextthreadnum (), 0);    }
The Init method is called directly at the time of construction

    private void Init (Threadgroup g, Runnable Target, String name, long stackSize) {if (name        = = null) {throw new NullPointerException ("name cannot be null");        } Thread Parent = CurrentThread ();        SecurityManager security = System.getsecuritymanager ();  if (g = = null) {/* Determine if it's an applet or not */* if there is a security manager, ask the Security Manager.            */if (security! = null) {g = Security.getthreadgroup (); }/* If the security doesn ' t has a strong opinion of the matter use the parent thread group.            */if (g = = null) {g = Parent.getthreadgroup (); }}/* CheckAccess regardless of whether or not threadgroup be explicitly passed in. */G.C        Heckaccess ();         /* * Do we have the required permissions? */if (sEcurity! = null) {if (Isccloverridden (GetClass ())) {Security.checkpermission (subclass_implemen            Tation_permission);        }} g.addunstarted ();        This.group = g;        This.daemon = Parent.isdaemon ();        This.priority = Parent.getpriority ();        THIS.name = Name.tochararray (); if (Security = = NULL | | Isccloverridden (PARENT.GETCLASS ())) This.contextclassloader = Parent.getcontextclassloa        Der ();        else This.contextclassloader = Parent.contextclassloader;        This.inheritedaccesscontrolcontext = Accesscontroller.getcontext ();        This.target = target;        SetPriority (priority); if (parent.inheritablethreadlocals! = null) This.inheritablethreadlocals = Threadlocal.createinh        Eritedmap (parent.inheritablethreadlocals);        /* Stash The specified stack size in case the VM cares */this.stacksize = stackSize; /* Set Thread ID */tid = NEXTTHReadid (); }
There are more things in it, but we can see that it initializes a variable runnable target;

Let's take a look at what's in the Run method here.

    @Override public    Void Run () {        if (target! = null) {            target.run ();        }    }
The original run method would first infer whether the runnable target variable was initialized, assuming there is no null implementation, assuming that target is not NULL, run the Runnable interface first. Some friends might guess that the following code calls the Run method in the Runnable interface before calling the Run method in the thread implementation class.

/* * Thread Call Priority */new thread (new Runnable () {@Overridepublic void run () {try {thread.sleep ()} catch (Interruptedexcepti On e) {e.printstacktrace ();} while (true) {System.out.println ("Runnable");}}) {public void Run () {try {sleep ()}, catch (Interruptedexception e) {e.printstacktrace ();} while (true) {System.out.println ("Thread");}};}. Start ();
In fact, this is not the case, because the above code is an anonymous inner class, which is actually a kind of inheritance and implementation from thread, so the following run method overrides the Run method in thread, so the Run method in runnable does not run at all.

Then look at the source code of the Runnable interface

Publicinterface Runnable {    /**     * When a object implementing interface <code>Runnable</code> is used     * To create a thread, starting the thread causes the object ' s     * <code>run</code> method to be called In that separately executing     * thread.     * <p> * The general contract of the method <code>run</code> are that it could take any     action wha Tsoever.     *     * @see     java.lang.thread#run () */public    abstract void run ();
Discover that the Runnable interface has only an abstract run method.

Why do you have a runnable interface to implement multithreading? Is it more convenient to inherit from thread? The runnable interface has advantages such as the following, so we often choose to implement the Runnable interface:

1, suitable for multiple program code threads to process the same resource.

public class     ThreadTest1 extends Thread {private int count = 5; public void Run () {for (int i = 0; i < 7; i++) {if (Count > 0) {System.out.print            ln ("count=" + count--); }}} public static void Main (string[] args) {//This is actually the creation of three non-affected thread instances ThreadTest1 t1 = new Threadt        Est1 ();        ThreadTest1 t2 = new ThreadTest1 ();        ThreadTest1 t3 = new ThreadTest1 ();        T1.start ();        T2.start ();    T3.start (); }}
public class threadtest1{public         static void Main (String [] args) {        MyThread my = new MyThread ();        Three threads are turned on, but the same run method        new Thread (My, "form 1th") is being manipulated. Start ();        New Thread (My, "No. 2nd Form"). Start ();        New Thread (My, "No. 3rd Form"). Start ();    } }class MyThread implements runnable{     private int ticket = 5;  5 Tickets public     void Run () {for        (int i=0; i<=20; i++) {            if (This.ticket > 0) {                System.out.println (T Hread.currentthread (). GetName () + "selling Ticket" +this.ticket--);}}}    

2. Avoid the limitations of single-root inheritance in Java features.

3. Ability to maintain separation of code and data (creation of threads and data independent).

4, more can embody the Java object-oriented design features.




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.