The join (), start (), run () method of the Java Multithreaded Series Foundation (eight)

Source: Internet
Author: User
Tags thread class

1. Join () Introduction

Join () is defined in Thread.java.
Join (): Lets the main thread wait for the "child threads" to end before they can continue to run. This sentence may be a bit obscure, we still use examples to understand:

Main thread public class Father extends Thread {public    void run () {        son s = new Son ();        S.start ();        S.join ();        ...    }} Child thread public class son extends thread {public    void run () {        ...    }}

Description :
There are two classes father (the main thread class) and son (child threading Class). Because son is created and started in father, Father is the main thread class and son is the child thread class.
In the father main thread, create a new child thread s through New Son (). The "Child thread S" is then started through S.start (), and S.join () is called. After calling S.join (), the Father main thread waits until the "child thread S" is finished, and after the "Child thread S" has finished running, the father main thread can then run. This is what we call the "join" function, which is to allow the main thread to wait for the child thread to end before it can continue to run!

2. Join () source analysis (based on jdk1.7.0_40)
Public final void Join () throws Interruptedexception {    join (0);} Public final synchronized void join (long Millis) throws Interruptedexception {    long base = System.currenttimemillis () ;    Long now = 0;    if (Millis < 0) {        throw new IllegalArgumentException ("Timeout value is negative");    }    if (Millis = = 0) {        while (isAlive ()) {            Wait (0),        }    } else {while        (IsAlive ()) {            long delay = mi Llis-now;            if (delay <= 0) {break                ;            }            Wait (delay);            now = System.currenttimemillis ()-Base;}}}    

Description :
From the code, we can see. When millis==0, it enters the while (IsAlive ()) loop, i.e. the main thread waits as long as the child thread is alive.
We understand the use of join () based on the code above explaining the function of join ()!
Questions :
Although S.join () is called in the "Father Main Thread", S.join () is the join () called by "Child thread S". Then, IsAlive () in the Join () method should be judged as "child thread S" is not alive state; the corresponding wait (0) should also be "let child thread S" wait. But if this is the case, how can s.join () be "Let the main thread wait until the child thread S is finished", should be let "the child thread waits for the right (because call the child thread object s's Wait method)"?
answer : The role ofwait () is to have the "current thread" wait, and here the "current thread" refers to the thread that is currently running on the CPU. So, although it is called the Wait () method of the child thread, it is called through the "main thread", so the main thread is dormant, not "child thread"!

Note: Before you understand this problem, you need to know which threads run (), start (), join (), and how the normal methods are executed by each thread, to understand that the thread execution method and the object invocation method are different, the following methods are explained below:

 Public class extends Thread {    publicvoid  run () {        ...    }
}

public class Test {
public static void Main (string[] args) {
   Son s = new Son ();
   S.start (); 1
S.run (); 2
S.join ();//3
}
}

As on the code, there is the main thread main and thread s:

1) If you write only the S.start () code at comment 1, which means that the S object calls its start () method, wait for the s thread to get the CPU to execute the object's Run method, which is performed by the S thread.

2) If you write only the S.run () code at Comment 2, the S object calls its run () method, which is executed by the main thread (the current thread).

3) If you write only the S.join () code at Comment 3, which means that the S object calls its join () method, like the run () method, it is the same as the normal class method, which is independent of the normal call and the thread class, so the method is executed by the main thread (the current thread). So the wait () method in the source code of the Join method is called by the S object,

But executed by the main method, the main method is the current thread, so the main method waits instead of the s thread.

To summarize the situation as above:

Operating mode Difference
Running Run only When running run only, the order of execution of multiple threads is executed in code order, except that the thread being executed is the current thread, not the thread you defined, such as: you run within the main function defined threads 1, 2, 3. Then only call 1.run (), 2.run (), 3.run (), the running thread is actually the main thread, and 1, 2, 3 does not matter, this time the thread class is equivalent to the ordinary class, call the Run method, the equivalent of invoking a common class method (the Join method is the same)
Run only start This time will be the implementation of the task to the Task planner, the execution of the specific thread needs to wait for the system to schedule, the task execution time and order is not certain, but these tasks are definitely run by your definition of the thread, rather than run only when the phenomenon, the current actively called the thread will not participate in the execution of these tasks, For example, like running run only, main does not define the tasks within the thread.
3. Join () Example

After understanding the role of join (), follow the example to see the use of join ().

Jointest.java source public class jointest{public     static void Main (string[] args) {         try {            Threada t1 = new Threa DA ("T1"); New "Thread T1"            t1.start ();                     Start "Thread T1"            t1.join ();                        The thread T1 is added to the main thread main, and the main thread main () waits for its completion            System.out.printf ("%s finish\n", Thread.CurrentThread (). GetName ( ));         } catch (Interruptedexception e) {            e.printstacktrace ();        }    }     Static class Threada extends thread{public        Threada (String name) {             super (name);         }         public void Run () {             System.out.printf ("%s start\n", This.getname ());             Delay operation for            (int i=0; I <1000000; i++)               ;            System.out.printf ("%s finish\n", This.getname ());         }     } }

Operation result :

T1 STARTT1 Finishmain Finish

Result Description :
Run the process
(01) Create a new thread T1 through new Threada ("T1") in main thread main. Next, start thread T1 with T1.start () and execute T1.join ().
(02) after executing t1.join (), "main thread main" will enter "blocking state" to wait for T1 to finish running. After the "Child thread T1" ends, it wakes up "main thread main", "Main thread" regain CPU execution and continue running.

Reprint:http://www.cnblogs.com/skywang12345/p/3479275.html

The join (), start (), run () method of the Java Multithreaded Series Foundation (eight)

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.