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

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 complete product is not easy, let's start from the thread step into the android inside.

First, Thread Foundation review

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 ();/* * The second way to create a thread */thread thread2 = new Thread (new Runnable () {@Overridepublic void run () {try {Thread.slee P (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 threads that we are familiar with, and if you are unfamiliar with them, look at the Java threading Basics.


Open the source code of the thread class can see that the thread class has 8 constructors, we first look at the two constructors above the source code.

    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 inside, but we can see that it initializes a variable runnable target;

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

    @Override public    Void Run () {        if (target! = null) {            target.run ();        }    }
The original Run method will first determine whether to initialize the runnable target variable, if there is no empty implementation, if target is not empty, first execute the Run method in the Runnable interface. 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 is not executed at all.

Now 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 the following advantages, 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, "window 1th") is being manipulated. Start ();        New Thread (My, Window No. 2nd). Start ();        New Thread (My, Window No. 3rd). 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. You can keep the separation of code and data (the number of threads created and the 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.