Detailed analysis of Java creation threads

Source: Internet
Author: User

reprint: http://shmilyaw-hotmail-com.iteye.com/blog/1880902Objective

The problem with threading creation can be said to be a cliché. In the beginning to learn the thread is basically exposed to, with a simple one or two words can be summed up. One is to create a class implementation runnable interface, and then pass an instance of the class as a parameter into the thread constructor. Call the Start method of the thread object again. Another way is to inherit the thread class and overwrite the Run method. The Start method is then called in the object instance. So, under what circumstances are these two ways applicable? Also, since the class we are going to implement is going to write the Run method, why do we call the Start method in the constructed instance? This is a lot of trouble, but also to go around a corner, I call the Run method directly do not? Wouldn't that be more convenient? For these questions, I will conduct detailed analysis and discussion in this article.

A typical thread creation process

This process can be said to be simple, the main two ways are as follows:

First, implement Runnable interface

The main three steps:

1. Implement the Runnable interface in the middle of the class

2. Create the object instance

3. Create a new thread object and pass the object as a parameter to the constructor

4. Call the Start method of the Thread object.

See the code below:

Java code
  1. Public class Threadcon implements Runnable
  2. {
  3. public Void Run ()
  4. {
  5. System.out.println ("Entering the test thread ...");
  6. Try
  7. {
  8. Thread.Sleep (5000);
  9. System.out.println ("Thread executing ...");
  10. Thread.Sleep (5000);
  11. }
  12. catch (interruptedexception e)
  13. {
  14. E.printstacktrace ();
  15. }
  16. }
  17. public static void Main (string[] args)
  18. {
  19. Threadcon con = new Threadcon ();
  20. Thread thread = new Thread (con);
  21. Thread.Start ();
  22. SYSTEM.OUT.PRINTLN ("main thread");
  23. }
  24. }

Second, inherit the thread class

The main thing is two steps:

1. Integrate the thread class to implement the Run method.

2. Create an instance of the class and call the start () method.

Java code
  1. Public class Threadcon extends Thread
  2. {
  3. public Void Run ()
  4. {
  5. System.out.println ("Entering the test thread ...");
  6. Try
  7. {
  8. Thread.Sleep (5000);
  9. System.out.println ("Thread executing ...");
  10. Thread.Sleep (5000);
  11. }
  12. catch (interruptedexception e)
  13. {
  14. E.printstacktrace ();
  15. }
  16. }
  17. public static void Main (string[] args)
  18. {
  19. Threadcon thread = new Threadcon ();
  20. Thread.Start ();
  21. SYSTEM.OUT.PRINTLN ("main thread");
  22. }
  23. }

After looking at the two parts of the code, there are a few questions.

1. How are these two ways of creating threads defined in the thread class?

2. We inherit the class or implement the interface, we have to overwrite the run () This method, why do we call the Start method later? What is the relationship between them?

Let's take a look at the first question first.

Thread-dependent class structure

If we take a closer look at the implementation of the thread class and the Runnable interface, they will have such a relationship:

The thread class itself inherits the Runnable interface.

The definition of the Runnable interface itself is simple:

Java code
  1. Public interface Runnable {
  2. /** 
  3. * When a object implementing interface <code>Runnable</code> is used
  4. * To create a thread, starting the thread causes the object ' s
  5. * <code>run</code> method to being called in that separately executing
  6. * Thread.
  7. * <p>
  8. * The general contract of the method <code>run</code> are it may
  9. * Take any action whatsoever.
  10. *
  11. * @see Java.lang.thread#run ()
  12. */
  13. public abstract Void run ();
  14. }

The Run method defined in the middle of the thread class implements the specification of the Runnable interface:

Java code
    1. @Override
    2. public Void Run () {
    3. if (target! = null) {
    4. Target.run ();
    5. }
    6. }

The target in the above code is a runnable member variable, as defined in thread:

Java code
    1. /* What'll be run. */
    2. Private Runnable target;

Also, see the following constructor defined in the middle of the thread class:

Java code
    1. Public Thread (Runnable target) {
    2. Init (null, Target, "thread-" + nextthreadnum (), 0);
    3. }

It is not difficult for us to understand that we can pass it as a parameter to the thread constructor by constructing an object that implements the Runnable interface. This corresponds to our first process of creating and starting a thread.

For the second way, when we inherit the thread from a class, by covering the Run method, we have inherited the thread definition, so as long as the Start method is called, it corresponds to our second process of creating and starting the thread.

When we write here, we will find that there is a missing place. Just discussed the relationship between the object we are creating and the runnable, thread. But what exactly is the Start method, and what does it matter? We soon got to the next step.

The secret of the Start method

Let's take a look at the implementation of the Start () method in thread:

Java code
  1. /**
  2. * Causes this thread to begin execution; The Java Virtual machine
  3. * Calls the <code>run</code> method of this thread.
  4. * <p>
  5. * The result is this and the threads is running concurrently:the
  6. * Current thread (which returns the
  7. * <code>start</code> method) and the other thread (which executes its
  8. * <code>run</code> method).
  9. * <p>
  10. * It's never legal to start a thread more than once.
  11. * In particular, a thread is not being restarted once it has completed
  12. * Execution.
  13. *
  14. * @exception Illegalthreadstateexception If the thread was already
  15. * started.
  16. * @see #run ()
  17. * @see #stop ()
  18. */
  19. public synchronized Void Start () {
  20. /** 
  21. * This method isn't invoked for the main method thread or "system"
  22. * Group Threads Created/set up by the VM. Any new functionality added
  23. * To the The also is added to the VM.
  24. *
  25. * A Zero status value corresponds to state "NEW".
  26. */
  27. if (threadstatus! = 0)
  28. throw new Illegalthreadstateexception ();
  29. / * Notify The group that this thread was about to be started
  30. * So, it can be added to the group ' s list of threads
  31. * and the group ' s unstarted count can be decremented. */
  32. Group.add (this);
  33. Boolean started = false;
  34. try {
  35. Start0 ();
  36. started = true;
  37. } finally {
  38. try {
  39. if (!started) {
  40. Group.threadstartfailed (this);
  41. }
  42. } catch (Throwable ignore) {
  43. /* do nothing . If Start0 threw a throwable then
  44. It'll be passed up the call stack */
  45. }
  46. }
  47. }
  48. private native void Start0 ();

This part of the code is not actually long, and the main purpose here is to call the Start0 () method. And start0 This method in the code definition is a private native method. What does that mean? Indicates that the Start0 method is actually a local implementation method. This native method is not necessarily implemented in Java, or it may be an implementation of another language that creates a thread space inside the JVM and then loads the instructions defined inside the Run method into the space. This will enable the effect of creating a new thread. So, this is where the Start method can create threads of magic.

At the same time, it explains why we can't just call the Run method to expect it to generate a new thread. If we call the Run method directly, it is actually executed sequentially in our same thread. In the case where the new thread was started earlier, our code execution would look like this:

Java code
    1. Main thread
    2. Entering the test thread ...
    3. Executing ...

If we try to change the Thread.Start () inside the main function to Thread.run (), we will find that the result of the execution is as follows:

Java code
    1. Entering the test thread ...
    2. Thread executing ...
    3. Main thread

In this case, the run () method and the main function are actually executed in the same thread space. If we were to analyze it with some profile tools, we would see a scenario like this.

Comparison of two ways to create a thread

It is simpler and more straightforward to implement threads in a way that inherits them. But from a design standpoint, the defined class needs to have an inheritance relationship with the thread method. What if the class itself has other inheritance relationships to deal with? At this point, this is not the right way to go. In the design of Java itself and in the guidance of the idea of object-oriented design, we do not recommend the priority to consider the relationship of inheritance. A class can implement multiple interfaces, but can inherit only one parent class. Therefore, the adoption of the implementation of the Runnable interface is a more recommended approach.

Summarize

The method of implementing the interface is relatively more flexible with regard to how threads are created. Because this approach does not establish a fixed inheritance relationship with a class, it is better to later extend some. Creating a thread to call the Start method is because of a special effect in the Start method that causes the command of the Run method to execute in the new thread. If we call the Run method directly in an instance that implements the Runnable interface or inherits the thread object, this will not produce a new thread. This is why we must call the Start method.

Detailed analysis of Java creation threads

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.