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.