Android (Java) Learning Note 62: Implementation of Multithreading (code embodiment)

Source: Internet
Author: User

1  Packagecn.itcast_02;2 3 /*4 * This class is going to rewrite the run () method, why?5 * Not all code in the class needs to be executed by the thread. 6 * And at this point, in order to distinguish which code can be executed by the thread, Java provides a run () in the thread class to contain code that is executed by the thread. 7  */8  Public classMyThreadextendsThread {9 Ten @Override One      Public voidrun () { A         //Write your own code -         //System.out.println ("Good study, day Up"); -         //In general, code that is executed by threads must be time-consuming. So we use loops to improve the          for(intx = 0; x < 200; X + +) { - System.out.println (x); -         } -     } +  -}

After rewriting this mythread class, we then write the class, add the main method, create the object, call the class:

1  Packagecn.itcast_02;2 3 /*4 * Requirements: We want to implement multi-threaded program. 5 * How to achieve it?6 * Because threads are dependent on processes, we should create a process first. 7 * and the process is created by the system, so we should go to invoke the system function to create a process. 8 * Java is not directly called system functions, so we have no way to directly implement multithreaded programs. 9 * But what? Java can go to call C + + written programs to implement multithreaded programs. Ten * The system function creation process is called by C + + and then by Java to invoke such things, One * Then provide some classes for us to use. We can implement multithreaded programs.  A * So what are the classes provided by Java? - * Thread - * By looking at the API, we know there are 2 ways to implement multithreaded programs.  the  *  - * Way 1: Inherit the Thread class.  - * Steps - * A: Custom class Mythread inherits the thread class.  + * B:mythread class inside rewrite run ()? - * Why is the Run () method ? + * C: Create object A * D: Start thread at  */ -  Public classMythreaddemo { -      Public Static voidMain (string[] args) { -         //To create a thread object -         //MyThread my = new MyThread (); -         // //Start Thread in         //My.run (); -         //My.run (); to         //Why is the call to the run () method a single thread? +         //because the run () method directly calls is actually equivalent to the normal method call, so you see the effect of a single thread  -         //To see the effects of multithreading, you must say another method:start ()  the         //Interview Question: What is the difference between run () and start ()? *         //run (): just encapsulate the code executed by the thread, the direct call is the normal method  $         //start (): starts the thread first, and then the JVM calls the thread's run () method. Panax Notoginseng         //MyThread my = new MyThread (); -         //My.start (); the         // //illegalthreadstateexception: Illegal thread-state exception +         // //for what? Because this is equivalent to the My thread was called two times. Instead of two threads to start. The first one already started the thread, and the second start starts again with an error.  A         //My.start (); the  +         //create two different thread objects -MyThread my1 =NewMyThread (); $MyThread My2 =NewMyThread (); $  - My1.start (); - My2.start (); the     } -}

Execute code We see results such as: maybe someone will ask this first run of 0,1,2,3 ... So what's the output of that thread? (My1 or my2 threads?) ), we will answer the question below.

For the questions we have just raised, let's illustrate (we use code to achieve this):

This is a thread class that we wrote:

1  Packagecn.itcast_03;2 3  Public classMyThreadextendsThread {4 5      PublicMyThread () {6     }7     8      PublicMyThread (String name) {9         Super(name);Ten     } One  A @Override -      Public voidrun () { -          for(intx = 0; x < 100; X + +) { theSystem.out.println (GetName () + ":" +x); -         } -     } -}

Here we write the test class again:

1  Packagecn.itcast_03;2 3 /*4 * How do I get the name of a thread object?5 * Public final String getName (): Gets the name of the thread. 6 * How do I set the name of a thread object?7 * Public final void SetName (String name): Sets the name of the thread8  * 9 * How do I get the name of a thread object in a subclass other than the thread class?Ten * public static Thread CurrentThread (): Returns the currently executing thread object One * Thread.CurrentThread (). GetName () A  */ -  Public classMythreaddemo { -      Public Static voidMain (string[] args) { the         //To create a thread object -         //non-parametric construction +setxxx () -         //MyThread my1 = new MyThread (); -         //MyThread my2 = new MyThread (); +         // //Call method Set name -         //my1.setname ("Brigitte"); +         //My2.setname ("Elina"); A         //My1.start (); at         //My2.start (); -          -         //to name a thread by constructing a method with a parameter -         //MyThread my1 = new MyThread ("Brigitte"); -         //MyThread my2 = new MyThread ("Elina"); -         //My1.start (); in         //My2.start (); -          to         //What do I do if I want to get the name of the thread object where the main method is located? +         //In this case, the thread class provides a fun way to do this: -         //Public static Thread CurrentThread (): Returns the currently executing thread object the System.out.println (Thread.CurrentThread (). GetName ()); *     } $ }Panax Notoginseng  - /* the Why is the name: thread-? number, the following is the source :(note here I just intercept I need, easy to understand and explain)  +  A class Thread { the private Char name[]; +  - Public Thread () { $ init (null, NULL, "thread-" + nextthreadnum (), 0); $     } -      - private void Init (Threadgroup g, Runnable Target, String name, the long StackSize) { - Init (g, Target, name, stackSize, null);Wuyi     } the      - private void Init (Threadgroup g, Runnable Target, String name, Wu long StackSize, AccessControlContext ACC) { - //Most of the code is omitted About this.name = Name.tochararray (); $     } -      - Public final void SetName (String name) { - this.name = Name.tochararray (); A     } +      the      - private static int threadinitnumber;//0,1,2 $ private static synchronized int nextthreadnum () { the return threadinitnumber++;//return 0,1 the     } the      the Public final String getName () { - return string.valueof (name); in     } the } the  About class MyThread extends Thread { the Public MyThread () { the super (); the     } + } -  the */

Attached to the executive:

It has to be said that such a thread name is not targeted, people say is not? Of course we can take the name of the thread ourselves, call the setName () method

Android (Java) Learning Note 62: Implementation of Multithreading (code embodiment)

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.