A simple summary of the Java threading method join

Source: Internet
Author: User
Tags thread class

First, the role

The primary role of the Join method in the thread class is synchronization, which enables parallel execution between threads to become serial execution. See the code specifically:

public class Jointest {public    static void Main (String [] args) throws interruptedexception {        Threadjointest t1 = New Threadjointest ("Xiaoming");        Threadjointest t2 = new Threadjointest ("small East");        T1.start ();        /**join means that the execution of the current thread is discarded and the corresponding thread is returned, for example, the following code means that the         program calls the join method of the T1 thread in the main thread, and the main thread discards the CPU control and returns the T1 thread to continue execution until the thread T1 execution is complete.         so the result is T1 thread execution, only to the main thread execution, equivalent to synchronize the T1 thread in main threads, T1 executes, the main thread has the opportunity to execute         *        /T1.join ();        T2.start ();    }} Class Threadjointest extends thread{public    threadjointest (String name) {        super (name);    }    @Override public    Void Run () {for        (int i=0;i<1000;i++) {            System.out.println (this.getname () + ":" + i);        }    }}

The above program results are printed on the small thread, in the printing of small East threads;

The above comment also describes the role of the Join method: when a B-thread's Join () method is called in a thread, it means that a thread can continue execution only when the B thread finishes executing. Note that the Join method called here is not a parameter, and the join method can actually pass an argument to it, see the following simple example:

public class Jointest {public    static void Main (String [] args) throws interruptedexception {        Threadjointest t1 = New Threadjointest ("Xiaoming");        Threadjointest t2 = new Threadjointest ("small East");        T1.start ();        The/**join method can pass parameters, join (10) indicates that the main thread will wait for the T1 thread 10 milliseconds, 10 milliseconds past,         * The execution order between the main thread and T1 thread is changed from serial execution to normal parallel execution        /T1.join ( (ten);        T2.start ();    }} Class Threadjointest extends thread{public    threadjointest (String name) {        super (name);    }    @Override public    Void Run () {for        (int i=0;i<1000;i++) {            System.out.println (this.getname () + ":" + i);        }    }}

The result of the above code is: The program executes 10 milliseconds before the print is Xiaoming thread, after 10 milliseconds, xiaoming and the small East program alternately print.

Therefore, if a parameter is passed in the Join method, it means that if the a thread is dropped with a join of the B thread (10), the A thread waits for the B thread to execute for 10 milliseconds, and after 10 milliseconds, the A and B threads execute in parallel. It is important to note that the JDK specifies that join (0) does not mean that a thread waits for the B thread for 0 seconds, but that a thread waits for the b thread for an unlimited time until the B thread executes, that is, join (0) is equivalent to join ().

  

Second, join and start call order problem

The above discussion probably knows the role of join, so what happens if the join joins are called before start? Let's look at the test results below.

public class Jointest {public    static void Main (String [] args) throws interruptedexception {        Threadjointest t1 = New Threadjointest ("Xiaoming");        Threadjointest t2 = new Threadjointest ("small East");        The/**join method can be called before the Start method and does not play the role of synchronization         *        /T1.join ();        T1.start ();        Thread.yield ();        T2.start ();    }} Class Threadjointest extends thread{public    threadjointest (String name) {        super (name);    }    @Override public    Void Run () {for        (int i=0;i<1000;i++) {            System.out.println (this.getname () + ":" + i);        }    }}

The result of the above code execution is: xiaoming and small East thread alternately print.

So we get the following conclusion: The Join method must be called after the thread start method is called to make sense. This is also very easy to understand: If a thread does not have a start, then it will not be synchronized.

Three, the Join method realization principle

With the above example, we probably know how the Join method works, so what is the implementation of the Join method?

In fact, the join method is done by calling the thread's wait method to achieve the purpose of synchronization. For example, a thread called the Join method of the B thread, which is equivalent to a thread called the wait method of the B thread, after the call of the wait method of the B thread, a thread will go into a blocking state, the following source:

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 = mil Lis-now;                if (delay <= 0) {break                    ;                }                Wait (delay);                now = System.currenttimemillis ()-Base;}}}    

As you can see from the source code, the principle of the Join method is to invoke the wait method of the corresponding thread, such as a join method that calls the B thread in a thread, which is equivalent to invoking the wait method of the B thread in the A thread, when the B thread finishes (or arrives at the wait time). The B thread automatically calls its own Notifyall method to wake the a thread, thus achieving synchronization.

A simple summary of the Java threading method join

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.