Java multi-thread Eight join () method parsing

Source: Internet
Author: User
Understanding the Join () method

First, let's look at an example:

public class Joindemo implements Runnable {
    private static int n = 0;

    public void Run () {for
        (int i = 0; i < 5; i++) {
            n + = 1
        ;
    }

    } public static void Main (string[] args) {
    t   hread t = new Thread (new Joindemo ());
        T.start ();
         * * Note TimeUnit.SECONDS.sleep (a);
         * * * Note two t.join ();
         *
        /SYSTEM.OUT.PRINTLN (n);
    }

}

I actually want the output of this program to be 5, but it's usually difficult to do this. The reason is as follows: when the main thread main () executes to SYSTEM.OUT.PRINTLN (n) this statement, thread T may be allocating resources ready to run, But it's not really running yet. Because the thread needs to allocate resources at startup, when the main () method finishes T.start () followed by the execution of SYSTEM.OUT.PRINTLN (n), the result may be a value that hasn't changed yet.
So how do I get the expected value of 5? Now that the thread takes a while before it actually runs, then I can add the code of annotation One after the T.start () method, so that the main thread sleeps for a while and waits for the thread T to start.
Now look at note two and add T.join () after T.start (), and you can also get results 5. So what does the join () method do?
Simple point: T.join () completes the thread T execution. In combination with the above example, when thread T calls the Join () method on a thread, the thread is suspended until the thread T completes execution and then continues execution. The
Join () method can be used with a time-out parameter so that if thread t expires at this time, the join () method can also be returned so that the current thread continues to run.

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.